【问题标题】:Why does HttpRequestMessage.Content.Headers.ContentType throw null reference exception?为什么 HttpRequestMessage.Content.Headers.ContentType 会抛出空引用异常?
【发布时间】:2020-07-22 07:51:28
【问题描述】:

这是我的代码:

 string bound = "----------------------------" +DateTime.Now.Ticks.ToString("x");
 HttpRequestMessage httpreq = new HttpRequestMessage();
 httpreq.Content.Headers.ContentType = new MediaTypeHeaderValue("multipart/form-data; boundary=" + bound);

抛出以下异常:

对象引用未设置为对象的实例。 System.Net.Http.HttpRequestMessage.Content.get 返回 null。

我不知道为什么会这样。

谁能帮我更正我的代码?

【问题讨论】:

  • 试试这个if (httpreq.Content == null) { httpreq.Content = new StringContent(""); }
  • 这个怎么用?你能提供完整的代码吗?

标签: c# uwp-xaml


【解决方案1】:

HttpRequestMessage.Content.Headers.ContentType在c#中抛出空引用异常?

System.Net.Http api用于跨平台。而且它不能完全支持UWP。在 UWP 平台我们建议您使用Windows.Web.Http 命名空间来替换。

using Windows.Web.Http;


string bound = "----------------------------" + DateTime.Now.Ticks.ToString("x");
HttpRequestMessage httpreq = new HttpRequestMessage();
httpreq.Content.Headers.ContentType = new Windows.Web.Http.Headers.HttpMediaTypeHeaderValue("multipart/form-data; boundary=" + bound);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-01-09
    • 2022-01-05
    • 2022-09-30
    • 1970-01-01
    • 2021-03-04
    • 2021-04-28
    • 2013-09-04
    • 1970-01-01
    相关资源
    最近更新 更多