System.Web.Mvc.AuthorizeAttribute not working with NinjectDependencyResolver
-
23-04-2021 - |
题
I have created an ASP.Net MVC Web Application and used NuGet to install Ninject version 2.2.1.4 and Ninject.MVC3 version 2.2.2.0. This application uses forms authentication. I am having a problem getting Authorization to work...
This is my Application_Start method in Global.asax:
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
RegisterGlobalFilters(GlobalFilters.Filters);
RegisterRoutes(RouteTable.Routes);
var kernel = new StandardKernel();
// binding code goes here...
// Remove this dependency resolver and Authorisation will work...
DependencyResolver.SetResolver(new NinjectDependencyResolver(kernel));
}
And one of my actions in my controller:
[Authorize(Roles = "Admin")]
public ActionResult About()
{
return View();
}
And the authenitcation section of my web.config:
<authentication mode="Forms">
<forms loginUrl="~/Account/LogOn" timeout="2880" />
</authentication>
The problem is that un-authorized users go staright to the About view instead of being redirected to the LogOn. I know that the problem is with the NinjectDependencyResolver becuase when I remove the "DependencyResolver.SetResolver..." line from the Application_Start un-authorized users are redirected.
I would be grateful for your help.
Regards, Phil
解决方案
You shoudn't set the DependencyResolver yourself.
Read the documentation https://github.com/ninject/ninject.web.mvc/wiki/Setting-up-an-MVC3-application about how to set up an MVC application using this extension.