简体   繁体   English

ASP.NET Web API不返回XML

[英]ASP.NET Web API not returning XML

I have a controller and method that adds user to a DB. 我有一个控制器和方法,可以将用户添加到数据库。

I call it from Fiddler with a Request Header as follows - 我从Fiddler用请求标题调用它如下 -

Content-Type: application/xml Content-Type:application / xml

Accept: application/xml 接受:application / xml

Host: localhost:62236 主持人:localhost:62236

Content-Length: 39 内容长度:39

And a request body of - 和请求机构 -

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

This works as expected, the method is called, the user object processed in the method PostUser. 这按预期工作,该方法被调用,用户对象在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;
        }
    }

I am performing my Model Validation in it's own class 我在它自己的类中执行模型验证

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);
        }
    }
}

BUT if I post the following 但如果我发布以下内容

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

The Model is invalid, and a JSON response is returned even though I stated Accept: application/xml. 模型无效,即使我声明Accept:application / xml,也会返回JSON响应。

If I perform model validation within the UserController, I get a proper XML response, but when I perform it in ModelValidationFilterAttribute I get JSON. 如果我在UserController中执行模型验证,我会得到一个正确的XML响应,但是当我在ModelValidationFilterAttribute中执行它时,我得到了JSON。

Your problems with the following code: 你有以下代码的问题:

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

So you try to create the response from the errors object where its type is Dictionary<string, IEnumerable<string>>(); 因此,您尝试从errors对象创建响应,其类型为Dictionary<string, IEnumerable<string>>(); .

Web.API will try to automatically find the right MediaTypeFormatter for your response type. Web.API将尝试为您的响应类型自动查找正确的MediaTypeFormatter However the default XML serializer ( DataContractSerializer ) not able to handle the type Dictionary<string, IEnumerable<string>>(); 但是默认的XML序列化程序( DataContractSerializer )无法处理类型Dictionary<string, IEnumerable<string>>(); so it will use the JSON serializer for your response. 所以它将使用JSON序列化程序进行响应。

Actually you should use the CreateErrorResponse and just create the response from the ModelState directly (it will create a HttpError object which is XML seriazable) 实际上你应该使用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);
        }
    }
}

I think the Web API will return JSON as its default type for responses outside of controller methods. 我认为Web API将返回JSON作为控制器方法之外的响应的默认类型。

Have you tried disabling the JSON formatter, as suggested in this article? 您是否尝试过禁用JSON格式化程序,如本文所述?

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

ie

void ConfigureApi(HttpConfiguration config)
{

    // Remove the JSON formatter
    config.Formatters.Remove(config.Formatters.JsonFormatter);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM