ASP.NET Core MVC still supports the concept of action filters. On the project I’m currently working on I wanted to add a global Authorization filter.
So similar to ASP.NET MVC, I tried to add the AuthorizeAttribute as a global filter:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class Startup | |
{ | |
// Removed all other code | |
// This method gets called by the runtime. Use this method to add services to the container. | |
public void ConfigureServices(IServiceCollection services) | |
{ | |
// Add framework services | |
services | |
.AddMvc(opt=> | |
{ | |
opt.Filters.Add(typeof(AuthorizeAttribute)); | |
}); | |
} | |
} |
However this didn’t work. In ASP.NET Core MVC the Attribute class and the filter implementation are separated from each other. Instead I had to use the following code:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class Startup | |
{ | |
// Removed all other code | |
// This method gets called by the runtime. Use this method to add services to the container. | |
public void ConfigureServices(IServiceCollection services) | |
{ | |
var policy = new AuthorizationPolicyBuilder() | |
.RequireAuthenticatedUser() | |
.Build(); | |
// Add framework services | |
services | |
.AddMvc(opt=> | |
{ | |
opt.Filters.Add(new AuthorizeFilter(policy)); | |
}); | |
} | |
} |