Samw
Samw

Reputation: 128

c# mvc3 controller having a overall if-statement

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

Answers (4)

user1082916
user1082916

Reputation:

In the case of ASP.Net MVC framework, I prefer to implement ActionFilterAttribute class....

Upvotes: 0

Rich Tebb
Rich Tebb

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

Cheng Chen
Cheng Chen

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

Peter Kiss
Peter Kiss

Reputation: 9329

I would create a class by implementing IRouteConstraint for this and build up my routing with it.

Upvotes: 1

Related Questions