您可以ExecuteAsync
使用实际序列InvalidModelStateResult
化BadRequest()
.ApiController
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);
}
}