【问题标题】:How to send a pushover notification with attached image in C# .NET如何在 C# .NET 中发送带有附加图像的推送通知
【发布时间】:2018-08-04 15:41:21
【问题描述】:

我正在尝试使用 C# .NET 通过 Pushover API附加图像 发送推送通知。以下代码返回 json 格式错误“message cannot be blank”。但是消息变量不为空。由于 SSL 已过时,我尝试明确使用 TLS 1.2。没有图像参数也会出现同样的错误。

public async Task PushImage(string title, string message, Stream image, string userKey, string appKey)
{
    // This does not work - error "message cannot be blank"
    using (HttpClient httpClient = new HttpClient())
    {
        //specify to use TLS 1.2 as default connection
        ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;

        MultipartFormDataContent form = new MultipartFormDataContent();
        form.Add(new StringContent(appKey), "token");
        form.Add(new StringContent(userKey), "user");
        form.Add(new StringContent(message), "message");
        var imageParameter = new StreamContent(image);
        imageParameter.Headers.ContentType = MediaTypeHeaderValue.Parse("image/png");
        form.Add(imageParameter, "attachment", "image.png");
        // Remove content type that is not in the docs
        foreach (var param in form)
            param.Headers.ContentType = null;

        HttpResponseMessage responseMessage = await httpClient.PostAsync(BaseApiUrl, form);
        if (responseMessage.IsSuccessStatusCode)
            return;

        string contentText = responseMessage.Content.ReadAsStringAsync().Result;
        var response = JsonConvert.DeserializeObject<PushResponse>(contentText);
        throw new ApplicationException(
            $"Push image request failed with status {(int)responseMessage.StatusCode} {responseMessage.StatusCode}: {response.Errors.JoinStrings(". ") ?? ""}");
    }
}

结果:

{"message":"cannot be blank","errors":["message cannot be blank"],"status":0,"request":"94152901-3b8f-45d6-ae6b-f7fc10b3439c"}

我通过查尔斯查看了原始请求,它或多或少与docs 所建议的一样。但是有一个小的区别。

Curl - 有效 - 产生如下所示的参数:

--------------------------30e0433d33c92cae
Content-Disposition: form-data; name="message"

my message
--------------------------30e0433d33c92cae--

HttpClient - 还不能工作 - 为每个参数生成这个:

--70ae375f-ef30-4885-8a8a-d38363080024
Content-Disposition: form-data; name=message

my message
--70ae375f-ef30-4885-8a8a-d38363080024--

注意引号的区别。如果我截取 Charles 中的消息并将参数名称用双引号括起来,并将 Content-Length 增加相同的数量,它可以工作

【问题讨论】:

    标签: c# .net pushover


    【解决方案1】:

    原来需要用双引号将参数名括起来,像这样:

    form.Add(new StringContent(appKey), "\"token\"");
    form.Add(new StringContent(userKey), "\"user\"");
    form.Add(new StringContent(message), "\"message\"");
    ...
    form.Add(imageParameter, "\"attachment\"", "image.png");
    

    别问我为什么。我只想继续我的生活,忘记我花了一整天调试这个问题......

    【讨论】:

    • 干得好,回来尝试减轻别人的痛苦!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多