开发者

Controller tests ignore global filters in ASP.Net MVC?

开发者 https://www.devze.com 2023-03-25 09:16 出处:网络
An ASP.Net MVC 3 application I\'ve just started writing needs to have authentication for all controllers with the exception of the AccountsController. Instead of decorating all of my controllers with

An ASP.Net MVC 3 application I've just started writing needs to have authentication for all controllers with the exception of the AccountsController. Instead of decorating all of my controllers with [Authenticate] I've written two custom attributes. The first inherits from AuthorizationAttribute and it checks to see if the current action is decorated with the other, AllowAnonymous. If it isn't it uses Forms Authentic开发者_Python百科ation to see if the current user is authenticated and redirects to the login page if not.

To apply this to all of the controllers I've added my custom authorization attribute to the GlobalFilterCollection in RegisterGlobalFilters in global.asax.cs.

This all works in the browser but I was surprised when I ran the default tests that come with an MVC Internet app to see that the HomeControllerTest test for the home page passed and said that the "Welcome To ASP.NET MVC" text was in the ViewBag. I would have expected this test to fail as when viewed in a browser this action would redirect to the login page unless a user had logged in.

Is my approach to authentication wrong or do I need to write something in the tests to apply the global filters? Stepping through the unit tests suggests that the filters are being added but they're not applied in the way I expect.


Your approach sounds fine. However, you will need to test controllers and action filters separately. See the following question

0

精彩评论

暂无评论...
验证码 换一张
取 消