【问题标题】:ASP.NET Web API not returning XMLASP.NET Web API 不返回 XML
【发布时间】:2013-01-14 18:19:21
【问题描述】:

我有一个将用户添加到数据库的控制器和方法。

我从 Fiddler 调用它,请求标头如下 -

内容类型:应用程序/xml

接受:应用程序/xml

主机:本地主机:62236

内容长度:39

还有一个请求体——

<User>
  <Firstname>John</Firstname>
  <Lastname>Doe</Lastname>
</User>

这按预期工作,方法被调用,用户对象在 PostUser 方法中处理。

 public class UserController : ApiController
    {
        public HttpResponseMessage PostUser(User user)
        {
            // Add user to DB
            var response = new HttpResponseMessage(HttpStatusCode.Created);
            var relativePath = "/api/user/" + user.UserID;
            response.Headers.Location = new Uri(Request.RequestUri, relativePath);
            return response;
        }
    }

我正在它自己的类中执行我的模型验证

public class ModelValidationFilterAttribute : ActionFilterAttribute
{
    public override void OnActionExecuting(HttpActionContext actionContext)
    {
        if (actionContext.ModelState.IsValid == false)
        {
            // Return the validation errors in the response body.
            var errors = new Dictionary<string, IEnumerable<string>>();
            foreach (KeyValuePair<string, ModelState> keyValue in actionContext.ModelState)
            {
                errors[keyValue.Key] = keyValue.Value.Errors.Select(e => e.ErrorMessage);
            }

            actionContext.Response =
                actionContext.Request.CreateResponse(HttpStatusCode.BadRequest, errors);
        }
    }
}

但是如果我发布以下内容

<User>
  <Firstname></Firstname> **//MISSING FIRST NAME**
  <Lastname>Doe</Lastname>
</User>

模型无效,即使我声明 Accept: application/xml,也会返回 JSON 响应。

如果我在 UserController 中执行模型验证,我会得到正确的 XML 响应,但是当我在 ModelValidationFilterAttribute 中执行它时,我会得到 JSON。

【问题讨论】:

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


    【解决方案1】:

    您对以下代码的问题:

    var errors = new Dictionary<string, IEnumerable<string>>();
    actionContext.Request.CreateResponse(HttpStatusCode.BadRequest, errors);
    

    因此,您尝试从类型为 Dictionary&lt;string, IEnumerable&lt;string&gt;&gt;();errors 对象创建响应。

    Web.API 将尝试自动为您的响应类型找到正确的MediaTypeFormatter。然而,默认的 XML 序列化程序 (DataContractSerializer) 无法处理 Dictionary&lt;string, IEnumerable&lt;string&gt;&gt;(); 类型,因此它将使用 JSON 序列化程序进行响应。

    实际上,您应该使用CreateErrorResponse 并直接从ModelState 创建响应(它将创建一个可XML 序列化的HttpError 对象)

    public class ModelValidationFilterAttribute : ActionFilterAttribute
    {
        public override void OnActionExecuting(HttpActionContext actionContext)
        {
            if (actionContext.ModelState.IsValid == false)
            {
                actionContext.Response =
                    actionContext.Request.CreateErrorResponse(
                        HttpStatusCode.BadRequest, 
                        actionContext.ModelState);
            }
        }
    }
    

    【讨论】:

    • 过去一个小时让我发疯了,很好的答案,它拯救了我的理智!
    • 因此,如果我有 Accept 标头 application/xml,并设置了 UseXmlSerializer,这应该与 Request.CreateResponse 一起使用,还是总是尝试使用 DataContractSerializer?无论哪种方式,它都不适合我。
    • @GlacialSpoon XmlSerializer 也不会序列化字典,因此您需要使用可序列化的类型。
    • @nemesv 谢谢。原来我忘记了 XmlSerializer 在模型上需要无参数构造函数。
    【解决方案2】:

    我认为 Web API 将返回 JSON 作为控制器方法之外的响应的默认类型。

    您是否尝试过按照本文的建议禁用 JSON 格式化程序?

    http://www.asp.net/web-api/overview/formats-and-model-binding/json-and-xml-serialization

    void ConfigureApi(HttpConfiguration config)
    {
    
        // Remove the JSON formatter
        config.Formatters.Remove(config.Formatters.JsonFormatter);
    }
    

    【讨论】:

      猜你喜欢
      • 2015-08-17
      • 1970-01-01
      • 2013-08-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多