The code is like:
[HttpPost]
public ResultEntityVM Register([FromBody,Required] RegisterParam createAssessorParam)
{
if (ModelState.IsValid == false)
{
return null;
}
//other code
ResultEntityVM vm = new ResultEntityVM();
return vm;
}
When the parameter createAssessorParam
is null
, the value of ModelState.IsValid
is true
. Why?
If I want to auto judge the parameter is null
or not, what can I do?
Don't I can only write the code:
if(RegisterParam != null)
{
//other
}
I've run into the same problem and solved it by implementing a custom action filter attribute evaluating all the validation attributes of the action method parameters.
I described the approach in this blog post, where I use ASP.NET Core 1.0, but the same approach should work with ASP.NET 4 as well.
here is @MarkVincze's answer adjusted for asp.net web
public class ValidateModelStateAttribute : System.Web.Http.Filters.ActionFilterAttribute
// there are two ActionFilterAttribute, one for MVC and another one for REST
{
/// <summary>
/// Called before the action method is invoked
/// </summary>
/// <param name="context"></param>
public override void OnActionExecuting(HttpActionContext context)
{
var parameters = context.ActionDescriptor.GetParameters();
foreach (var p in parameters)
{
if (context.ActionArguments.ContainsKey(p.ParameterName))
Validate(p, context.ActionArguments[p.ParameterName], context.ModelState);
}
if (!context.ModelState.IsValid)
{
context.Response = context.Request.CreateResponse(
HttpStatusCode.BadRequest,
context.ModelState.Select(_ => new { Parameter = _.Key, Errors = _.Value.Errors.Select(e => e.ErrorMessage ?? e.Exception.Message) }),
context.ControllerContext.Configuration.Formatters.JsonFormatter
);
}
}
private void Validate(HttpParameterDescriptor p, object argument, ModelStateDictionary modelState)
{
var attributes = p.GetCustomAttributes<ValidationAttribute>();
foreach (var attr in attributes)
{
if (!attr.IsValid(argument))
modelState.AddModelError(p.ParameterName, attr.FormatErrorMessage(p.ParameterName));
}
}
}
In WebAPI, an action parameter will never be null. It is always instantiated by the framework. So you would rather use the Required
attribute on the properties of your view model if you want to ensure that they are present.
来源:https://stackoverflow.com/questions/31892333/required-attribute-on-action-parameter-doesnt-work