编程语言
首页 > 编程语言> > c# – 如何使用Forbidden状态web api返回ModelState

c# – 如何使用Forbidden状态web api返回ModelState

作者:互联网

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

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也没有返回相同的东西.如何将ModelState的BadRequest()方法使用的序列化方法与其他状态代码一起使用?

解决方法:

您可以使用InvalidModelStateResult的ExecuteAsync方法(ApiController的BadRequest()方法的返回类型)来实现所需的输出,该方法实际上序列化了ModelState.

因此,我们的想法是创建一个新类,该类扩展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);
    }
}

标签:c,serialization,asp-net-web-api,modelstate,modelstatedictionary
来源: https://codeday.me/bug/20190710/1427101.html