如何实现IHttpActionResult以使其尊重Accept标头?

时间:2016-03-22 17:56:27

标签: c# asp.net-web-api2

我想在我的ApiController中覆盖BadRequest(),以便它返回一个带有验证错误的对象。这是我实现“RichBadRequest”结果的第一个错误:

public class RichBadRequestResponse : BadRequestResult
{
    public IEnumerable<string> Errors { get; set; } = new string[0];
    public string Message { get; set; }

    private HttpRequestMessage _request;
    public RichBadRequestResponse(HttpRequestMessage request) : base(request)
    {
        _request = request;
    }

    public override Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken)
    {
        var dataObj = new
        {
            errors = Errors.ToArray(),
            message = Message ?? string.Join(", ", Errors)
        };
        if (_request.Headers.Accept.Contains(new MediaTypeWithQualityHeaderValue("applicaiton/xml")))
        {
            Console.WriteLine("Foo");
        }
        var resp = _request.CreateResponse(HttpStatusCode.BadRequest, dataObj);
        return Task.FromResult(resp);
    }
}

然后在我的控制器中我只有:

public class MyApiController : ApiController
{
    protected override BadRequestResult BadRequest()
    {
        return BadRequest("There was an error with your request", null);
    }

    protected RichBadRequestResponse BadRequest(string message, IEnumerable<string> validationErrors)
    {
        validationErrors = validationErrors ?? new string[0];
        var result = new RichBadRequestResponse(Request)
        {
            Message = "There was an error with your request",
            Errors = validationErrors.ToArray()
        };
        return result;
    }
}

这很好用...... 然而它不尊重Accept标头。无论出于何种原因,这似乎总是作为JSON对象返回。我做错了什么?

1 个答案:

答案 0 :(得分:2)

通过你的i发现,当CreateErrorResponse返回JSON / XML或根据Accept标头时,CreateResponse没有返回XML。

在CreateErrorResponse中,您可以根据需要添加词典集合。

    public override Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken)
    {
        var dataObj = new
        {
            errors = errors.ToArray(),
            message = Message ?? string.Join(", ", errors)
        };

        if (_request.Headers.Accept.Contains(new MediaTypeWithQualityHeaderValue("applicaiton/xml")))
        {
            Console.WriteLine("Foo");
        }
        ///// Changed Line
        var resp = _request.CreateErrorResponse(HttpStatusCode.BadRequest, yourDictionaryCollection);
        return Task.FromResult(resp);
    }