0

我怎样才能返回一个仅由其根元素组成的非常简单的 xml?就像是: <?xml version="1.0" encoding="UTF-8"?> <myelement> somevalue </myelement>

问题是没有子元素,所以我不知道我应该编写什么类型的 POCO 类来获得该输出。我一直在尝试的是返回一个字符串,但我最终得到

<string>somevalue</string>

我是 WebApi 的新手,所以任何建议都将不胜感激!

4

1 回答 1

0

我敢打赌这不是最好的解决方案,但它现在正在工作:

public class MyCustomFormatter : ActionFilterAttribute
{
    public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
    {
        HttpResponseMessage response = actionExecutedContext.Response;
        var contentType = response.Content.Headers.ContentType;
        var oldContents = response.Content.ReadAsStringAsync().Result;
        oldContents = oldContents.Replace("string", "myelement");
        response.Content = new StringContent("<?xml version=\"1.0\" encoding=\"utf-8\"?>" + oldContents);
        response.Content.Headers.ContentType = contentType;
        actionExecutedContext.Response.Content = response.Content;
    }
}
于 2013-02-21T13:40:43.757 回答