我正在尝试将一个长字符串(包含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();
}
答案 0 :(得分:2)
将XML作为内容发送而不使用Uri编码。