I have this filter that I am trying to run
public class ModelValidationAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext context)
{
context.Result = new NotFoundResult();
}
}
I have placed it above my post controller like this
[HttpPost]
[Route("Save")]
[ModelValidation]
public ActionResult Save(CreateUserDto Input)
{
CreateUserViewModel cuvm = new CreateUserViewModel
{
Id = Input.Id,
UserName = Input.UserName,
Email = Input.Email,
FirstName = Input.FirstName,
LastName = Input.LastName,
DateOfBirth = Input.DateOfBirth,
PhoneNumber = Input.PhoneNumber,
Password = Input.Password,
ConfirmPassword = Input.ConfirmPassword,
RoleList = Input.RoleList,
CreatedOn = Input.CreatedOn,
UpdatedOn = Input.UpdatedOn
};
//if (!ModelState.IsValid)
//{
// return BadRequest(Input);
//}
var result = applicationUsersData.Save(cuvm);
if (Input.RoleList != null)
{
var RoleList = JsonConvert.DeserializeObject<List<UserAddRoleDetailsViewModel>>(Input.RoleList);
foreach (var item in RoleList)
{
var uardvm = new SaveUserRolesDetailsViewModel
{
RoleId = item.Id,
Id = result.Id
};
userRolesData.Save(uardvm);
}
}
return Ok();
}
However, the filter doesn't trigger at all. How can I ensure that it runs? I have tried registering it in Startup.cs but that did not work as well.
EDIT: Startup.cs
services.AddAuthorization(options =>
{
options.AddPolicy(RoleGlobals.SystemAdministrator, policy => policy.Requirements.Add(new RolesFilter(RoleGlobals.SystemAdministrator, ApplicationGlobals.ApplicationName)));
});
services.AddMvc(options => {
options.Filters.Add(new ModelValidationAttribute());
});
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…