这个answer from 2012给了我这个从POST读取原始XML的解决方案:
[HttpPost]
[Route("raw")]
public HttpResponseMessage ReadRaw(HttpRequestMessage rawRequest)
{
var requestDocument = XDocument.Parse(rawRequest.Content.ReadAsStringAsync().Result);
var request = MyDBContext.GetStuffStaticMethod(requestDocument);
var responseDocument = request.GetResponseDocument(this._context);
var xml = responseDocument.ToString();
return new HttpResponseMessage
{
Content = new StringContent(xml, Encoding.UTF8, "application/xml")
};
}
这仍然是目前时间范围内的方式吗?
BTW:这是我基于OWIN的集成测试的请求:
using (WebApp.Start<Startup>(url: baseUri))
{
var client = new HttpClient();
HttpResponseMessage response = null;
Func<string, string> callOwin = i =>
{
var requestUri = baseUri + i;
this.TestContext.WriteLine("requestUri: {0}", requestUri);
response = client.PostAsync(requestUri,
new StringContent(requestDoc.ToString(SaveOptions.DisableFormatting), Encoding.UTF8, "text/xml")).Result;
this.TestContext.WriteLine("response: {0}", response.ToString());
return response.Content.ReadAsStringAsync().Result;
};
var xml = callOwin(path);
Assert.IsNotNull(response, "The expected response is not here.");
Assert.AreEqual(HttpStatusCode.OK, response.StatusCode, "The expected response status code is not here.");
Assert.IsFalse(string.IsNullOrEmpty(xml), "A response is expected.");
this.TestContext.WriteLine("xml: {0}", xml);
}
答案 0 :(得分:0)
考虑this article from Microsoft evangelist Darrel Miller。他向我们展示了[FromBody]
和XElement
的组合是可行的方法:
[HttpPost]
[Route("raw")]
public IHttpActionResult ReadRaw([FromBody]XElement rootElement)
{
var requestDocument = new XDocument(rootElement);
var request = MyDBContext.GetStuffStaticMethod(requestDocument);
var responseDocument = request.GetResponseDocument(this._context);
return this.Ok<XElement>(responseDocument.Root);
}