Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
228 views
in Technique[技术] by (71.8m points)

c# - Action Filter Attribute doesn't run

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Be sure to implement System.Web.Mvc.ActionFilterAttribute and not System.Web.Http.Filters.ActionFilterAttribute


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...