If you are using Session Authorization in your MVC Application then you need to check the existence of the session in each controller method.
In order to avoid this, you can make your own attribute that inherits from AuthorizeAttribute, and by overriding AuthorizeCore and HandleUnauthorizedRequest methods. You can place this attribute on the needed controllers.
Following is the code for the Custom Attribute to check the session
AuthorizeSessionAttribute.cs
In a controller method
If you want a single method need to by pass this session Authorization then you need to put the [AllowAnonymous] attribute to that method as below
In order to avoid this, you can make your own attribute that inherits from AuthorizeAttribute, and by overriding AuthorizeCore and HandleUnauthorizedRequest methods. You can place this attribute on the needed controllers.
Following is the code for the Custom Attribute to check the session
AuthorizeSessionAttribute.cs
public class AuthorizeSessionAttribute : AuthorizeAttribute { protected override bool AuthorizeCore(HttpContextBase httpContext) { return httpContext.Session["UserID"] != null; } protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext) { filterContext.Result = new RedirectResult("/account/login"); } }Usage:
In a controller method
public class SomeController : Controller { [AuthorizeSession] public ActionResult Index() { } }In a controller
[AuthorizeSession] public class SomeController : Controller { public ActionResult Index() { } }Here it will applies to all the methods in the controller.
If you want a single method need to by pass this session Authorization then you need to put the [AllowAnonymous] attribute to that method as below
[AuthorizeSession] public class SomeController : Controller { public ActionResult Index() { } [AllowAnonymouse] public ActionResut publicpage() { } }
0 comments:
Post a Comment