112

我想知道如何使用 ASP.NET Web API 实现模型验证。我的模型是这样的:

public class Enquiry
{
    [Key]
    public int EnquiryId { get; set; }
    [Required]
    public DateTime EnquiryDate { get; set; }
    [Required]
    public string CustomerAccountNumber { get; set; }
    [Required]
    public string ContactName { get; set; }
}

然后我的 API 控制器中有一个 Post 操作:

public void Post(Enquiry enquiry)
{
    enquiry.EnquiryDate = DateTime.Now;
    context.DaybookEnquiries.Add(enquiry);
    context.SaveChanges();
}

如何添加if(ModelState.IsValid)并处理错误消息以传递给用户?

4

11 回答 11

192

为了关注点分离,我建议您使用操作过滤器进行模型验证,因此您无需太在意如何在您的 api 控制器中进行验证:

using System.Net;
using System.Net.Http;
using System.Web.Http.Controllers;
using System.Web.Http.Filters;

namespace System.Web.Http.Filters
{
    public class ValidationActionFilter : ActionFilterAttribute
    {
        public override void OnActionExecuting(HttpActionContext actionContext)
        {
            var modelState = actionContext.ModelState;

            if (!modelState.IsValid)
                actionContext.Response = actionContext.Request
                     .CreateErrorResponse(HttpStatusCode.BadRequest, modelState);
        }
    }
}
于 2012-07-30T15:18:37.137 回答
32

也许不是你想要的,但也许有人知道:

如果您使用的是 .net Web Api 2,您可以执行以下操作:

if (!ModelState.IsValid)
     return BadRequest();

根据模型错误,您会得到以下结果:

{
   Message: "The request is invalid."
   ModelState: {
       model.PropertyA: [
            "The PropertyA field is required."
       ],
       model.PropertyB: [
             "The PropertyB field is required."
       ]
   }
}
于 2014-05-16T14:56:27.077 回答
29

像这样,例如:

public HttpResponseMessage Post(Person person)
{
    if (ModelState.IsValid)
    {
        PersonDB.Add(person);
        return Request.CreateResponse(HttpStatusCode.Created, person);
    }
    else
    {
        // the code below should probably be refactored into a GetModelErrors
        // method on your BaseApiController or something like that

        var errors = new List<string>();
        foreach (var state in ModelState)
        {
            foreach (var error in state.Value.Errors)
            {
                errors.Add(error.ErrorMessage);
            }
        }
        return Request.CreateResponse(HttpStatusCode.Forbidden, errors);
    }
}

这将返回这样的响应(假设为 JSON,但 XML 的基本原理相同):

HTTP/1.1 400 Bad Request
Content-Type: application/json; charset=utf-8
(some headers removed here)

["A value is required.","The field First is required.","Some custom errorm essage."]

您当然可以以任何您喜欢的方式构建错误对象/列表,例如添加字段名称、字段 ID 等。

即使它是一个“单向”的 Ajax 调用,例如一个新实体的 POST,您仍然应该向调用者返回一些东西——指示请求是否成功的东西。想象一个网站,您的用户将通过 AJAX POST 请求添加一些关于他们自己的信息。如果他们尝试输入的信息无效怎么办 - 他们如何知道他们的保存操作是否成功?

最好的方法是使用Good Old HTTP Status Codes之类200 OK的。这样,您的 JavaScript 就可以使用正确的回调(错误、成功等)正确处理故障。

这是关于此方法的更高级版本的一个很好的教程,使用 ActionFilter 和 jQuery:http ://asp.net/web-api/videos/getting-started/custom-validation

于 2012-07-27T11:21:17.003 回答
9

或者,如果您正在为您的应用程序寻找简单的错误集合。这是我的实现:

public override void OnActionExecuting(HttpActionContext actionContext)
    {
        var modelState = actionContext.ModelState;

        if (!modelState.IsValid) 
        {

            var errors = new List<string>();
            foreach (var state in modelState)
            {
                foreach (var error in state.Value.Errors)
                {
                    errors.Add(error.ErrorMessage);
                }
            }

            var response = new { errors = errors };

            actionContext.Response = actionContext.Request
                .CreateResponse(HttpStatusCode.BadRequest, response, JsonMediaTypeFormatter.DefaultMediaType);
        }
    }

错误消息响应将如下所示:

{
  "errors": [
    "Please enter a valid phone number (7+ more digits)",
    "Please enter a valid e-mail address"
  ]
}
于 2016-12-26T04:21:13.697 回答
6

在 startup.cs 文件中添加以下代码

services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2).ConfigureApiBehaviorOptions(options =>
            {
                options.InvalidModelStateResponseFactory = (context) =>
                {
                    var errors = context.ModelState.Values.SelectMany(x => x.Errors.Select(p => new ErrorModel()
                   {
                       ErrorCode = ((int)HttpStatusCode.BadRequest).ToString(CultureInfo.CurrentCulture),
                        ErrorMessage = p.ErrorMessage,
                        ServerErrorMessage = string.Empty
                    })).ToList();
                    var result = new BaseResponse
                    {
                        Error = errors,
                        ResponseCode = (int)HttpStatusCode.BadRequest,
                        ResponseMessage = ResponseMessageConstants.VALIDATIONFAIL,

                    };
                    return new BadRequestObjectResult(result);
                };
           });
于 2019-11-05T05:56:51.170 回答
4

C#

    public class ValidateModelAttribute : ActionFilterAttribute
    {
        public override void OnActionExecuting(HttpActionContext actionContext)
        {
            if (actionContext.ModelState.IsValid == false)
            {
                actionContext.Response = actionContext.Request.CreateErrorResponse(
                    HttpStatusCode.BadRequest, actionContext.ModelState);
            }
        }
    }

...

    [ValidateModel]
    public HttpResponseMessage Post([FromBody]AnyModel model)
    {

Javascript

$.ajax({
        type: "POST",
        url: "/api/xxxxx",
        async: 'false',
        contentType: "application/json; charset=utf-8",
        data: JSON.stringify(data),
        error: function (xhr, status, err) {
            if (xhr.status == 400) {
                DisplayModelStateErrors(xhr.responseJSON.ModelState);
            }
        },
....


function DisplayModelStateErrors(modelState) {
    var message = "";
    var propStrings = Object.keys(modelState);

    $.each(propStrings, function (i, propString) {
        var propErrors = modelState[propString];
        $.each(propErrors, function (j, propError) {
            message += propError;
        });
        message += "\n";
    });

    alert(message);
};
于 2016-09-07T07:27:00.897 回答
3

在这里你可以检查以一一显示模型状态错误

 public HttpResponseMessage CertificateUpload(employeeModel emp)
    {
        if (!ModelState.IsValid)
        {
            string errordetails = "";
            var errors = new List<string>();
            foreach (var state in ModelState)
            {
                foreach (var error in state.Value.Errors)
                {
                    string p = error.ErrorMessage;
                    errordetails = errordetails + error.ErrorMessage;

                }
            }
            Dictionary<string, object> dict = new Dictionary<string, object>();



            dict.Add("error", errordetails);
            return Request.CreateResponse(HttpStatusCode.BadRequest, dict);


        }
        else
        {
      //do something
        }
        }

}

于 2016-02-17T05:58:25.353 回答
2

我在实现可接受的解决方案模式时遇到问题,对于某些模型对象,我ModelStateFilter总是会返回false(随后返回 400) :actionContext.ModelState.IsValid

public class ModelStateFilter : ActionFilterAttribute
{
    public override void OnActionExecuting(HttpActionContext actionContext)
    {
        if (!actionContext.ModelState.IsValid)
        {
            actionContext.Response = new HttpResponseMessage { StatusCode = HttpStatusCode.BadRequest};
        }
    }
}

我只接受 JSON,所以我实现了一个自定义模型绑定器类:

public class AddressModelBinder : System.Web.Http.ModelBinding.IModelBinder
{
    public bool BindModel(HttpActionContext actionContext, System.Web.Http.ModelBinding.ModelBindingContext bindingContext)
    {
        var posted = actionContext.Request.Content.ReadAsStringAsync().Result;
        AddressDTO address = JsonConvert.DeserializeObject<AddressDTO>(posted);
        if (address != null)
        {
            // moar val here
            bindingContext.Model = address;
            return true;
        }
        return false;
    }
}

我在我的模型之后直接注册

config.BindParameter(typeof(AddressDTO), new AddressModelBinder());
于 2015-10-11T23:54:40.037 回答
1

您还可以抛出异常,如此处所述:http: //blogs.msdn.com/b/youssefm/archive/2012/06/28/error-handling-in-asp-net-webapi.aspx

请注意,要执行该文章的建议,请记住包含 System.Net.Http

于 2014-07-11T17:47:51.890 回答
0

把它放在 startup.cs 文件中

 services.AddMvc().ConfigureApiBehaviorOptions(options =>
        {
            options.InvalidModelStateResponseFactory = (context) =>
            {
                var errors = context.ModelState.Values.SelectMany(x => x.Errors.Select(p =>p.ErrorMessage)).ToList();                    
                var result = new Response
                {
                    Succeeded = false,
                    ResponseMessage = string.Join(", ",errors)
                };
                return new BadRequestObjectResult(result);
            };
        });
于 2022-01-27T10:12:24.623 回答