【发布时间】: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