基于方糖的微信服务号通知
需要安装两个库
- RestSharp
- RestSharp.Serializers.NewtonsoftJson
代码如下:
using System.Diagnostics;
using Newtonsoft.Json;
using RestSharp;
using RestSharp.Serializers.NewtonsoftJson;
// 方糖官网:https://sct.ftqq.com/
IPush<FangTangInput, FangTangOutput> push = new FangTangPush(new FangTangConfig("your key"));
var output = push.Send(new FangTangInput("测试用例","这是一条测试内容。"));
Console.WriteLine("response: {0}", output.Content);
/**
* output:
* response: {"code":0,"message":"","data":{"pushid":"128222432","readkey":"SCTwh4qB51Q25EY","error":"SUCCESS","errno":0}}
*/
public interface IPush<in TInput, out TOutput>
{
public TOutput Send(TInput input);
}
public class PushResponse
{
public string Content { get; set; }
}
public class FangTangConfig
{
public FangTangConfig(string key)
{
Key = key;
}
public string Key { get; set; }
}
public class FangTangInput
{
public FangTangInput()
{
}
public FangTangInput(string title, string desp)
{
Title = title;
Desp = desp;
}
public string Title { get; set; }
public string Desp { get; set; }
}
public class FangTangOutput : PushResponse
{
public string PushId { get; set; }
public string ReadKey { get; set; }
public string Error { get; set; }
public int ErrNo { get; set; }
}
public class FangTangPush : IPush<FangTangInput, FangTangOutput>
{
private RestClient _client;
private const string BaseUrl = "https://sctapi.ftqq.com/";
private FangTangConfig _config;
public FangTangPush(FangTangConfig config)
{
this._config = config;
var options = new RestClientOptions(BaseUrl);
_client = new RestClient(
options
, configureSerialization: s => s.UseNewtonsoftJson()
);
}
/// <inheritdoc />
public FangTangOutput Send(FangTangInput input)
{
var resource = $"{this._config.Key}.send";
RestRequest restRequest = new RestRequest(resource, Method.Post).AddJsonBody(input);
var restResponse = this._client.Post(restRequest);
Debug.Assert(restResponse.Content != null, "restResponse.Content != null");
var output = JsonConvert.DeserializeObject<FangTangOutput>(restResponse.Content);
Debug.Assert(output != null, nameof(output) + " != null");
output.Content = restResponse.Content;
return output;
}
}