csharp 用于处理.net模型状态的可重用ValidationFilter属性

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了csharp 用于处理.net模型状态的可重用ValidationFilter属性相关的知识,希望对你有一定的参考价值。

public class CustomerModel
{
    [Required]
    public int FirstName { get; set; }
  
    [Required]
    public int LastName { get; set; }
}
{
  "message": "The request is invalid.",
  "modelState": {
    "model.FirstName": [
      "The FirstName field is required."
    ],
    "model.LastName": [
      "The LastName field is required."
    ]
  }
}
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http.Filters;
using System.Web.Http.Controllers;
using System;
using System.Web.Http.ModelBinding;
using System.Collections.Generic;

namespace MyApp.Web.Infrastructure.Filters
{
    /// <summary>
    /// This action attribute is used to validate the view model. It will throw 422 - Unprocessable 
    /// entity in case model (modelState) was not validated.
    /// <see href="http://stackoverflow.com/questions/11686690/handle-modelstate-validation-in-asp-net-web-api"/>
    /// <seealso href="http://stackoverflow.com/a/3291292/413785"/>
    /// </summary>
    public class ValidationFilter : ActionFilterAttribute
    {
        public override void OnActionExecuting(HttpActionContext actionContext)
        {
            var modelState = actionContext.ModelState;

            var model = actionContext.ActionArguments["model"];
            if (model != null)
            {
                var modelType = model.GetType();
                dynamic modelObject = Convert.ChangeType(model, modelType);
                if (modelObject != null && modelType.GetMethod("Validate") != null)
                {
                    modelObject.Validate(modelState);
                }
            }

            if (!modelState.IsValid)
            {
                actionContext.Response = actionContext.Request.CreateErrorResponse((HttpStatusCode)422, modelState);
            }

            //base.OnActionExecuting(actionContext);
        }
    }
}
[ValidationFilter]
public IHttpActionResult PostCustomer(CustomerModel model)
{
    return Ok();
}

以上是关于csharp 用于处理.net模型状态的可重用ValidationFilter属性的主要内容,如果未能解决你的问题,请参考以下文章

csharp 有关如何使用app_code文件夹创建razorviews可以使用的可重用的html帮助程序的示例。这些将是.cshtml

具有 set Input() 任何类型的可重用组件是一个好习惯吗?

如何制作可用于可查询的可重用条件? [复制]

用于数据库访问的可重用函数

csharp 用于处理DataTables.net客户端表呈现插件的Ajax调用的C#代码。

Eclipse/Android 中的可重用项目