【问题标题】:How to post a long string containing XML to Web API如何将包含 XML 的长字符串发布到 Web API
【发布时间】:2014-08-13 12:18:50
【问题描述】:

我正在尝试将一个长字符串(包含 XML)发布到我的 Web API 控制器,但我失败得很惨。

如果 TextAsXml 很短,则以下内容有效,但是当 TextAsXml 很长时,它会失败“无效的 URI:Uri 字符串太长。”,这是可以理解的。

// Client code
using (var client = new HttpClient())
{
  var requestUri = "http://localhost:49528/api/some";
  var content = new FormUrlEncodedContent(new[] 
  {
    new KeyValuePair<string, string>("Author", "John Doe"),
    new KeyValuePair<string, string>("TextAsXml", "<?xml version=\"1.0\" encoding=\"UTF-8\"?><note><to>Tove</to><from>Jani</from><heading>Reminder</heading><body>Don't forget me this weekend!</body></note>")
  });

  var response = client.PostAsync(requestUri, content).Result;
  response.EnsureSuccessStatusCode();
}

// Controller code
public HttpResponseMessage Post(SomeModel someModel)
{
  // ...
  return Request.CreateResponse(HttpStatusCode.OK);
}

public class SomeModel
{
  public string Author { get; set; }
  public string TextAsXml { get; set; }
}

当 TextAsXml 很长时,如何使上述代码工作?我尝试使用 StringContent 和 MultipartContent,但无法正常工作。

// This results in 500 Internal server error.
using (var client = new HttpClient())
{
  var requestUri = "http://localhost:49528/api/some";
  var textAsXml = File.ReadAllText("Note.xml");
  var content = new MultipartFormDataContent();
  content.Add(new StringContent("John Doe"), "Author");
  content.Add(new StringContent(textAsXml), "TextAsXml");

  var response = client.PostAsync(requestUri, content).Result;
  response.EnsureSuccessStatusCode();
}

【问题讨论】:

    标签: c# xml httpclient asp.net-web-api


    【解决方案1】:

    将 XML 作为不带 Uri 编码的内容发送。

    【讨论】:

    • 那部分我已经弄清楚了 :-) 但是怎么做呢?正如您在导致 500 Internal Server Error 的示例中看到的那样,我正在使用 MultipartFormDataContent 调用 PostAsync,但没有成功。
    猜你喜欢
    • 1970-01-01
    • 2016-08-02
    • 2017-09-10
    • 1970-01-01
    • 2019-03-03
    • 1970-01-01
    • 2012-12-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多