I would like开发者_开发百科 to add a check for Request.IsAuthenticated into my MasterPage (COntroller? Is there such a thing??). Is this possible? I want to redirect to a NoAccess.aspx page if the check fails.
The concept on MVC is different to web forms where you would do common logic on the master.
In ASP.NET MVC master page must only contain UI related setup.
In MVC you use Action filters: decorate your actions with [Authorize]
.
Did you create a project using the default MVC project template? It has everything you're looking for already in there. If you didn't go ahead and create one now.
Once you're in there you'll notice the [Authorize]
attributes as @Aliostad mentioned. These are custom attributes that do the validation on the controller level.
Check out the MVC tutorial on web form security for a more detailed run-down on how it all meshes together: http://www.asp.net/mvc/tutorials/authenticating-users-with-forms-authentication-cs
You can achieve this by creating your own custom authentication attribute.
Create a new filter folder within your project and add the following class
public class NoAccessDirectAuthorizeAttribute : AuthorizeAttribute
{
public override void OnAuthorization(AuthorizationContext filterContext)
{
if (!filterContext.HttpContext.User.Identity.IsAuthenticated)
filterContext.Result = new RedirectResult("noaccess.aspx");
}
}
then decorate your home controller and other required controllers with the Authorization Attribute
[NoAccessDirectAuthorizeAttribute]
public class HomeController : Controller
This will redirect an unathenticated user to your noaccess.aspx page
精彩评论