4

我们可以ModelState通过BadRequest以下方式从 web api 返回:

return BadRequest(ModelState);

它提供以下输出:

{
    "Message": "The request is invalid.",
    "ModelState": {
        "property": [
            "error"
        ]
    }
}

如何返回与Forbidden状态相同的输出?

我尝试了以下方法:

return Content(HttpStatusCode.Forbidden, ModelState);

但它返回:

{
    "property": {
        "_errors": [
            {
                "<Exception>k__BackingField": null,
                "<ErrorMessage>k__BackingField": "error"
            }
        ],
        "<Value>k__BackingField": null
    }
}

Json 序列化ModelSate也不会返回相同的东西。如何将BadRequest()method for使用的序列化方法ModelState与其他状态代码一起使用?

4

1 回答 1

0

您可以ExecuteAsync使用实际序列InvalidModelStateResultBadRequest().ApiControllerModelState

所以想法是创建一个新类,它扩展InvalidModelStateResult和覆盖ExecuteAsync方法来更改状态代码。

public class ModelStateResult : InvalidModelStateResult
{
    private readonly HttpStatusCode _status;

    public ModelStateResult(ModelStateDictionary modelState, ApiController controller, HttpStatusCode status) : base(modelState, controller)
    {
        _status = status;
    }

    public override Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken)
    {
        var response = base.ExecuteAsync(cancellationToken).Result;
        response.StatusCode = _status;
        return Task.FromResult(response);
    }
}

像这样使用它:

return new ModelStateResult(ModelState, this, HttpStatusCode.Forbidden);    //this refers to ApiController here

我认为这只是一种解决方法,希望有人发布更好的方法来实现它。

编辑:

不使用InvalidModelStateResult

public class ModelStateResult : IHttpActionResult
{
    public HttpStatusCode Status { get; }
    public ModelStateDictionary ModelState { get; }
    public HttpRequestMessage Request { get; }

    public ModelStateResult(HttpStatusCode status, ModelStateDictionary modelState, HttpRequestMessage request)
    {
        Status = status;
        ModelState = modelState;
        Request = request;
    }

    public Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken)
    {
        var response = Request.CreateErrorResponse(Status, ModelState);
        return Task.FromResult(response);
    }
}
于 2017-09-04T10:49:31.143 回答