Reputation: 128
im new to c# but what im trying to do instead of having a if-statement in every actionresult.
can i have a overall if-statement for the controller and just run that for every actionresult?
public InformationController {
if (Session["CharacterName"] == null)
{
return RedirectToAction("logon", "Auth");
}
something like that?
Upvotes: 0
Views: 334
Reputation:
In the case of ASP.Net MVC framework, I prefer to implement ActionFilterAttribute class....
Upvotes: 0
Reputation: 7126
This looks like a prime candidate for an Action Filter. Something like this:
public class CheckSessionCharacterNameAttribute : FilterAttribute, IAuthorizationFilter
{
public void OnAuthorization(AuthorizationContext filterContext)
{
if (filterContext.HttpContext.Session["CharacterName"] == null)
{
filterContext.Result = new RedirectToRouteResult(...);
}
}
}
Upvotes: 1
Reputation: 43531
Create a ActionFilterAttribute
like this:
public class MyFilterAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
//your logic here
}
}
and apply this attribute to your controller
[MyFilter]
public class MyController : Controller
Upvotes: 1
Reputation: 9329
I would create a class by implementing IRouteConstraint for this and build up my routing with it.
Upvotes: 1