0

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?

1
  • 1
    No, conditionals like that (outside of a method body) are not valid syntax in C#. Have you looked into the Authorize attribute class and Forms Authentication? Seems like it would be easier to leverage what's already available. Commented Mar 6, 2012 at 9:10

4 Answers 4

1

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
Sign up to request clarification or add additional context in comments.

Comments

1

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

1 Comment

1

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(...);
        }
    }
}

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.