在ASP.NET的Web API模型绑定验证参数(Validating parameters in

2019-09-28 19:50发布

我有一个自定义IModelBinder为我的模型:

public class MyBinder : IModelBinder {

public bool BindModel(HttpActionContext actionContext, ModelBindingContext bindingContext) {
        // bla-bla-bla

        bindingContext.ModelState.AddModelError(
            bindingContext.ModelName, "Request value is invalid.");
        return false;
    }
}

我想到的是,当值无效的请求HTTP传递自动返回400错误的请求。 但是,这种情况不会发生。 我应该怎么做才能让网页API返回的HTTP 400,如果有任何约束力的错误?

Answer 1:

你可以做beautifulcoder建议但还有很多不足之处,因为你需要重复的每一个动作。 我建议你创造出onActionExecuting和onActionExecuted验证该ModelState中是有效的,并返回错误请求的ActionFilterAttribute。 然后,你可以把这个分开行动为[BadRequestIfModelNotValid]或全局过滤器把它应用到每一个请求。

public sealed class BadRequestIfModelNotValidAttribute : System.Web.Http.Filters.ActionFilterAttribute
{
  /// <summary>
  /// if the modelstate is not valid before invoking the action return badrequest
  /// </summary>
  /// <param name="actionContext"></param>
  public override void OnActionExecuting(System.Web.Http.Controllers.HttpActionContext actionContext)
  {
    var modelState = actionContext.ModelState;
    if (!modelState.IsValid)
      actionContext.Response = generateModelStateBadRequestResponse(modelState, actionContext.Request);

    base.OnActionExecuting(actionContext);//let other filters run if required
  }

  /// <summary>
  /// if the action has done additional modelstate checks which made it invalid we are going to replace the response with a badrequest
  /// </summary>
  /// <param name="actionExecutedContext"></param>
  public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
  {
    var modelState = actionExecutedContext.ActionContext.ModelState;
    if (!modelState.IsValid)
      actionExecutedContext.Response = generateModelStateBadRequestResponse(modelState, actionExecutedContext.Request);

    base.OnActionExecuted(actionExecutedContext);
  }

  private HttpResponseMessage generateModelStateBadRequestResponse(IEnumerable<KeyValuePair<string, ModelState>> modelState, HttpRequestMessage request)
  {
    var errors = modelState
      .Where(s => s.Value.Errors.Count > 0)
      .Select(s => new ApiErrorMessage {
          Parameter = s.Key,
          Message = getErrorMessage(s.Value.Errors.First())
        }) //custom class to normalize error responses from api
        .ToList();

    return request.CreateResponse(System.Net.HttpStatusCode.BadRequest, new ApiError
    {
      ExceptionType = typeof(ArgumentException).FullName,
      Messages = errors
    });
  }

  /// <summary>
  /// retrieve the error message or fallback to exception if possible
  /// </summary>
  /// <param name="modelError"></param>
  /// <returns></returns>
  private static string getErrorMessage(ModelError modelError)
  {
    if(!string.IsNullOrWhiteSpace(modelError.ErrorMessage))
      return modelError.ErrorMessage;

    if(modelError.Exception != null)
      return modelError.Exception.Message;

    return "unspecified error";
  }
}


Answer 2:

返回它在你的控制器:

if (!ModelState.IsValid)
{
    return new HttpResponseMessage(HttpStatusCode.BadRequest);
}


文章来源: Validating parameters in ASP.NET Web API model binder