【发布时间】:2020-06-03 04:51:48
【问题描述】:
这是我的控制器。我需要在执行操作方法之前验证输入参数。操作方法接受 Json 对象,但在方法内部我们会将其转换为模型对象。是否可以将输入验证为模型我的自定义操作过滤器中的对象?ValidateParamFilterAttribute 是我的自定义过滤器类,它应该接受操作方法作为参数。它应该是通用的,所以我不需要为我的应用程序中的每个操作方法重复它。
public class InputValidationController : ApiController
{
[HttpPost][ValidateParamFilter(typeof(Users))]
public string SaveData([FromBody]JObject testdata )
{
}
}
我的自定义操作过滤器:
public class ValidateParamFilterAttribute: Attribute , IActionFilter
{
public ValidateParamFilterAttribute(Type type) {
//not able to proceed here
// the type parameter will take my modal classes.in this case it should be Users
}
public override void OnActionExecuting(HttpActionContext actionContext)
{
}
}
模型类:
public class Users
{
[Required(ErrorMessage ="Id field is mandatory")]
public int id { get; set; }
[Required][StringLength(10,ErrorMessage ="Name length can't be more than 10")]
public string Name { get; set; }
[Required][Phone][MaxLength(10)]
public string PhoneNumber { get; set; }
[Required][EmailAddress]
public string Email { get; set; }
}
【问题讨论】:
-
这个案例有什么更新吗?你达到要求了吗?
标签: c# validation asp.net-core-webapi action-filter