Search code examples
asp.net-mvc-3event-handlinghttp-request

ASP .NET MVC 3 + Handling an HTTP request reception event


I have just started developing a full-web application by using the ASP .NET MVC 3 framework. I am a MVC 3 beginner developper.


I need a way to implement the following logic :

When my application receives an HTTP request from a browser I want to check if a session is valid with this browser.

If not, I want to execute the Index action method of my Connection controller. The Index action method returns an HTML5 page to the browser which lets the user authentificates himself to the application.

If a session is valid then I want to check if the IdUtilSession and IdSocSession session variables are stored. If both session variables are not stored then I want to execute the Index action method of my Connection controller.


I read some MSDN documentation about managing session variables. I think I am able to manage session variables in my application.

I want to know the event I have to handle - "When my application receives an HTTP request". I read the following MSDN documentation page on the ASP .NET application life cycle : http://msdn.microsoft.com/en-us/library/ms178473.aspx A sequence of events are triggered during the request processing from Do I need to handle one of these events in my Global.asax file ?

Thanks in advance for your future help


Solution

  • A more MVCish way to achieve this is to write a custom authorize attribute (instead of relying on events which are more commonly used in classic ASP.NET rather than ASP.NET MVC):

    public class MyAuthorizeAttribute : AuthorizeAttribute
    {
        protected override bool AuthorizeCore(HttpContextBase httpContext)
        {
            var authorized = base.AuthorizeCore(httpContext);
            if (!authorized)
            {
                return false;
            }
    
            var session = httpContext.Session;
            return session["IdUtilSession"] != null &&
                   session["IdSocSession "] != null;
        }
    }
    

    and then instead of using the default [Authorize] attribute use your custom [MyAuthorize] attribute.

    As far as the I want to execute the Index action method of my Connection controller part is concerned, you could set the loginUrl attribute in the <forms> tag in your web.config to point to the proper url.