使用flurl向OneSignal api发送通知

时间:2019-03-06 23:03:27

标签: .net core onesignal flurl

我正在尝试使用onesignal页面中的示例发送一些数据

var request = WebRequest.Create("https://onesignal.com/api/v1/notifications") as HttpWebRequest;

request.KeepAlive = true;
request.Method = "POST";
request.ContentType = "application/json; charset=utf-8";

request.Headers.Add("authorization", "Basic xxx");

var obj = new
{
    app_id = "xxx",
    contents = new { en = "English Message" },
    included_segments = new string[] { "Active Users" }
};
var param = JsonConvert.SerializeObject(obj);
byte[] byteArray = Encoding.UTF8.GetBytes(param);

使用此代码可以正常工作,但即时通讯使用Flurl像这样向单信号发出请求

var body = new
{
    app_id = "xxx",
    contents = new
    {
        es = "Mensaje prueba"

    },
    included_segments = new string[] { "All" }
};
string param = JsonConvert.SerializeObject(body);
var content = new System.Net.Http.ByteArrayContent(Encoding.UTF8.GetBytes(param));

var response = await new Flurl.Url(urlbase)
    .AppendPathSegment("notifications")
    .WithHeader("Content-Type", "application/json; charset=utf-8")
    .WithHeader("Authorization", "Basic xxx")
    .PostAsync(content)
    .ReceiveString();

但是我收到“错误请求”。请有人帮忙指出如何使用Flurl拨打同一电话?

1 个答案:

答案 0 :(得分:1)

如第一条评论所述,您要做的工作超出了您的需要。 Flurl将为您序列化body,因此请删除这些行:

string param = JsonConvert.SerializeObject(body);
var content = new System.Net.Http.ByteArrayContent(Encoding.UTF8.GetBytes(param));

然后直接使用body发布PostJsonAsync

var response = await urlbase
    ...
    .PostJsonAsync(body)
    .ReceiveString();