简体   繁体   中英

Redirecting Anonymous User or wrong user type to login page within a specific controller in ASP.net MVC 3

I have two sections to my site, one is the front end customer portal which serves as a storefront. The other is where merchants can edit their wares, prices and the look of their store page in the storefront.

The former can be accessed by anyone, anonymous user or customer accounts, but the latter should only be accessible by merchant accounts that are logged in. If someone attempts to use a link to access parts of the merchant site without being logged in as a merchant, they should be redirected to the merchant log in.

I have a few lines I can put at the top of every Action like this:

if (!(User.Identity.IsAuthenticated
    && User.IsInRole(VendorsController.Role)))
        return RedirectToAction("Login", "Vendors");

But adding that to the beginning of each action feels like it's bad practice. I've also seen a few posts about modifying the web.config but I think that's for an earlier version of MVC. Is there a way to create an event listener that interrupts an action call to redirect to login, if the user isn't logged in as the right user type? Or will I have to add this line of code to each action?

我会使用AuthenticationFilter在其中创建自定义 AuthenticationFilter 然后根据需要将其应用于控制器或操作

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM