操作过滤器属性未运行

时间:2018-10-06 15:02:44

标签: c# asp.net-core

我有要运行的过滤器

public class ModelValidationAttribute : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext context)
    {
        context.Result = new NotFoundResult();
    }
}

我已将其放置在我的后控制器上方

[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();
}

但是,过滤器根本不会触发。我如何确保其运行?我尝试在Startup.cs中注册它,但是效果不佳。

编辑: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());
});

1 个答案:

答案 0 :(得分:-1)

请务必实施System.Web.Mvc.ActionFilterAttribute而不是System.Web.Http.Filters.ActionFilterAttribute