Session is null in IRouteHandler.GetHttpHandler with Asp.net routing - asp.net

I'm trying to get Session enabled in the GettHttpHandler method of my IRouteHandler classes but session is always null. Could someone tell me what I'm doing wrong?
In global.asax I have
RouteTable.Routes.Add("All", new Route("{*page}", new MyRouteHandler()));
The MyRouteHandler class where Session is null looks like this:
public class MyRouteHandler : IRouteHandler, IRequiresSessionState
{
public System.Web.IHttpHandler GetHttpHandler(RequestContext requestContext)
{
string test = HttpContext.Current.Session["test"].ToString();
return BuildManager.CreateInstanceFromVirtualPath("~/Page.aspx", typeof(Page)) as Page;
}
}
I made a small test app that shows the problem.
Could someone tell me what I'm doing wrong?
Edited to add:
Yes, I really need session data in the route handler. There are many reasons but one easily explainable is when the user can switch to browse the site in preview mode.
The site consists of a hierarchy of dynamic pages (/page1/page2...) in the database that can be published normally or to preview. A content producer browsing the site can choose to view just normal pages or also those published to preview. The browsing mode is stored in the user's session so therefor the route handler needs to know the browsing mode to be able to solve the requested page.
So I really need the session already at that stage.

I have explained reason behind this problem in this answer. And now I have found a solution to the problem!
You create a custom HttpHandler class:
class MyHttpHandler : IHttpHandler, IRequiresSessionState
{
public MyRequestHandler RequestHandler;
public RequestContext Context;
public MyHttpHandler(MyRequestHandler routeHandler, RequestContext context)
{
RequestHandler = routeHandler;
Context = context;
}
public void ProcessRequest(HttpContext context)
{
throw new NotImplementedException();
}
public bool IsReusable
{
get { throw new NotImplementedException(); }
}
}
It is important to add IRequiresSessionState interface, otherwise IIS does not load session for this request. We do not need to implement logic of ProcessRequest and IsReusable, but class must implement the IHttpHandler interface.
You change your RouteHandler implementation:
public class MyRequestHandler : IRouteHandler
{
public IHttpHandler GetHttpHandler(RequestContext requestContext)
{
return new MyHttpHandler(this, requestContext);
}
public IHttpHandler DelayedGetHttpHandler(RequestContext requestContext)
{
// your custom routing logic comes here...
}
}
You simply move your original, Session dependent logic to DelayedGetHttpHandler function and in the GetHttphandler function you return an instance of the helping MyHttpHandler class.
Then, you hook your handling logic to the HttpApplication.PostAcquireRequestState event, e.g. in the Global.asax:
public class Global : HttpApplication
{
public override void Init()
{
base.Init();
PostAcquireRequestState += Global_PostAcquireRequestState;
}
}
For more reference, check this page: https://msdn.microsoft.com/en-us/library/bb470252(v=vs.140).aspx. It explains the request lifecycle and why I use the PostAcquireRequestState event.
In the event handler, you invoke your custom RouteHandling function:
void Global_PostAcquireRequestState(object sender, EventArgs e)
{
if (HttpContext.Current.Handler is MyHttpHandler) {
var handler = HttpContext.Current.Handler as MyHttpHandler;
HttpContext.Current.Handler = handler.RouteHandler.DelayedGetHttpHandler(handler.Context);
}
}
And that's it. Works for me.

I am not sure that you can do this (although I may be wrong). My recollection is that IRequiresSessionState indicates that an HttpHandler needs session state, rather than the route handler (which is responsible for giving you a handler appropriate to the route).
Do you really need the session in the route handler itself and not the handler it gives out?

Well I know this is old thread but just putting up the answer here if anyone like me falls in the same scenario, I found an answer here
What you do is just add a runAllManagedModulesForAllRequests="true" attribute to your modules tag in web.config like below
<system.webServer>
.....
<modules runAllManagedModulesForAllRequests="true">
........
</modules>
......
</system.webServer>
However this is not a good solution as it calls managed module everytime, i am using
<remove name="Session" />
<add name="Session" type="System.Web.SessionState.SessionStateModule"/>
add it in modules section of web.config, this a better solution than the previous one.

Related

How to obtain a reference to the default ASP.NET page handler or web-services handler?

Consider a Web.config file containing the following httpHandlers declaration:
<httpHandlers>
<add verb="*" path="*" type="MyWebApp.TotalHandlerFactory"/>
</httpHandlers>
In other words, this handler factory wants to “see” all incoming requests so that it gets a chance to handle them. However, it does not necessarily want to actually handle all of them, only those that fulfill a certain run-time condition:
public sealed class TotalHandlerFactory : IHttpHandlerFactory
{
public IHttpHandler GetHandler(HttpContext context, string requestType, string url, string pathTranslated)
{
if (some condition is true)
return new MySpecialHttpHandler();
return null;
}
public void ReleaseHandler(IHttpHandler handler) { }
}
However, doing it like this completely overrides the default ASP.NET handler, which means that ASP.NET pages and web services no longer work. I just get a blank page for every URL that doesn’t fulfill the “some condition” in the “if”. Therefore, it seems that returning null is the wrong thing to do.
So what do I need to return instead so that ASP.NET pages and web services are still handled normally?
I would have thought the easiest way would be for your class to inherit from System.Web.UI.PageHandlerFactory and then in an else clause just call base.GetHandler().
public sealed class TotalHandlerFactory : System.Web.UI.PageHandlerFactory
{
public IHttpHandler GetHandler(HttpContext context, string requestType, string url, string pathTranslated)
{
if (some condition is true)
return new MySpecialHttpHandler();
else
return base.GetHandler(context, requestType, url, pathTranslated)
}
}
I had the same problem, and seems that doing that is not possible using an HttpHandlerFactory.
But, I found a workaround that solved the problem: Using an HttpModule to filter which requests should go to my custom HttpHandler:
First, remove the any reference to your HttpHandler from the web.config.
Then, add a reference to the following HttpModule inside the <Modules> section:
public class MyHttpModule : IHttpModule
{
public void Dispose() { }
public void Init(HttpApplication application)
{
application.PostAuthenticateRequest += new EventHandler(application_PostAuthenticateRequest);
}
void application_PostAuthenticateRequest(object sender, EventArgs e)
{
var app = sender as HttpApplication;
var requestUrl = context.Request.Url.AbsolutePath;
if (requestUrl "meets criteria")
{
app.Context.RemapHandler(new MyHttpHandler());
}
}
}
Finally, assume at your HttpHandler that all the incoming request fulfill your criteria, and handle there all the requests.
Without knowing all of your requirements, it sounds like a HttpModule is a more suitable solution for your problem.
It is not possible to do this in the general case.

.net MVC 3 Request event

I am a little new to .net and trying to grasp a few concepts.
I have been writing in Coldfusion for a while, and in CF there is an event under the Application.cfc called onRequest() that fires each time there is a page.
What in .net is used to capture the request information?
And moreover is there a way to latch on or extend the Request event to fire off my own events?
You can also find global.asax file and use one of events of HttpApplication class (for example BeginRequest):
http://msdn.microsoft.com/en-us/library/system.web.httpapplication.aspx
HttpApplication has Request property.
You can catch every request there, not only related to Controller (images, css, wrong address).
public class MvcApplication : System.Web.HttpApplication
{
protected void Application_BeginRequest(object sender, EventArgs e)
{
//Request.Have_fun
}
}
If you don't want to write code in global.asax file, you should consider using HttpModule.
Create new class with this example code:
using System;
using System.Web;
namespace MyProject
{
public class MyHttpModule : IHttpModule
{
public void Init(HttpApplication application)
{
application.BeginRequest += ApplicationBeginRequest;
application.EndRequest += ApplicationEndRequest;
}
private void ApplicationEndRequest(object sender, EventArgs e)
{
//do something here with HttpContext.Current.Request
}
private static void ApplicationBeginRequest(Object source, EventArgs e)
{
//do something here with HttpContext.Current.Request
}
public void Dispose()
{
}
}
}
Add two entries in web.config (registers HttpModule):
<system.web>
<httpModules>
<add name="MyHttpModule" type="MyProject.MyHttpModule" />
</httpModules>
</system.web>
<system.webServer>
<modules runAllManagedModulesForAllRequests="true">
<add name="MyHttpModule" type="MyProject.MyHttpModule" />
</modules>
</system.webserver>
Because of changes in IIS7(adding system.webServer section), you have to add two entries in web.config.
You'll probably want something like OnActionExecuting which is called before the action is hit.
To access the current request you could do the following:
protected virtual void OnActionExecuting(ActionExecutingContext filterContext) {
//Do the default OnActionExecuting first.
base.OnActionExecuting(filterContext);
//The request variable will allow you to see information on the current request.
var request = filterContext.RequestContext.HttpRequest;
}
If you want to access this in every controller, then you should probably create a base controller and add this there.
public class BaseController : Controller
{
//Code above
}
And in your Home controller:
public class HomeController : BaseController
{
}
If you are working in ASP.NET MVC 3 I would recommend using global action filters (use one per "event" you want to handle) instead of tapping directly into the ASP.NET Application/Request stack.

ASP.Net MVC: How do you access the session from a different project within the solution?

I have 2 projects in my solution.
MVC Web application
Class library
The MVC Web application references the class library.
The class library contains a class that extends the default ASP.Net Controller.
I'm putting a variable in session in the application's Global.asax.
protected void Session_Start(object sender, EventArgs args)
{
HttpContext.Current.Session["DomainName"] = Request.Url.Host;
}
In the class library I'm trying to get the value from the HttpContext.Session, but HttpContext.Session keeps coming up null.
public class MyController : System.Web.Mvc.Controller
{
public MyController () : base()
{
//HttpContext.Session is always null at this point
ViewData["DomainName"] = HttpContext.Session["DomainName"];
}
}
HttpContext.Current.Session doesn't seem to be an option in controllers. Any ideas?
Two issues -- the HttpContext property in the Controller class is the current session. Unfortunately, it's not available in the constructor of the controller. Obviously because it's not passed in the constructor, it has to be set via the property afterwards. You might consider adding a property to hold the domain name and referencing the session from it -- that way it would be available for use when needed.
protected string DomainName
{
get { return this.HttpContext.Session["DomainName"] as string; }
}
The set it in ViewData in your actions or in OnActionExecuting/OnActionExecuted.
protected override void OnActionExecuted( ActionExecutedContext context )
{
ViewData["DomainName"] = this.HttpContext.Session["DomainName"];
// or ViewData["DomainName"] = this.DomainName; // if you used the property
}
If you're just trying to add ViewData from the session, try doing it in the OnActionExecuting method. This is where I typically add ViewData I want for every View.
You just use Session by itself (it's a property of Controller), but that just maps to Controller.HttpContext.Session (in other words, what you're already using), so it won't solve your problem, which must be elsewhere.
I'm not sure why you're putting this in the Session, though, as you can read Request.Url.Host directly during the Action.
When you create cookie then you must write
Response.AppendCookie("Your cookie name");
And if you want to get that then something like this
if (Request.Cookies["Your cookie name"] != null)
{
string value = Request.Cookies["Your cookie name"].Value;
}
and must if there are different solutions
then
machineKey
need to be same which is under
system.web
in web.config and then write
<httpCookies domain=".yourdomainname.com" />

Disable Session state per-request in ASP.Net MVC

I am creating an ActionResult in ASP.Net MVC to serve images. With Session state enabled, IIS will only handle one request at a time from the same user. (This is true not just in MVC.)
Therefore, on a page with multiple images calling back to this Action, only one image request can be handled at a time. It's synchronous.
I'd like this image Action to be asynchronous -- I'd like multiple image requests to each execute without needing the previous one to complete. (If the images were just static files, IIS would serve them up this way.)
So, I'd like to disable Session just for calls to that Action, or to specify that certain requests do not have Session state. Anyone know how this is done in MVC? Thanks!
If anyone is in the situation I was in, where your image controller actually needs read only access to the session, you can put the SessionState attribute on your controller
[SessionState(SessionStateBehavior.ReadOnly)]
See http://msdn.microsoft.com/en-us/library/system.web.mvc.sessionstateattribute.aspx for more info.
Thanks to https://stackoverflow.com/a/4235006/372926
Rather than implementing an action filter for this, why don't you implement a RouteHandler?
Here's the deal - IRouteHandler has one method - GetHttpHandler. When you make an ASP.Net MVC request to a controller, by default the routing engine handles the request by creating a new instance of MvcRouteHandler, which returns an MvcHandler. MvcHandler is an implementation of IHttpHandler which is marked with the (surprise!) IRequiresSessionState interface. This is why a normal request uses Session.
If you follow my blog post on how to implement a custom RouteHandler (instead of using MvcRouteHandler) for serving up images - you can skip returning a session-tagged IHttpHandler.
This should free IIS from imposing synchronicity on you. It would also likely be more performant because it's skipping all the layers of the MVC code dealing with filters.
I also came across the same problem and after doing R&D this link worked for me
Reference:
https://techatfingers.wordpress.com/2016/06/14/session-state-on-action/
Create custom Attribute
Override the “GetControllerSessionBehavior” method present in class DefaultControllerFactory.
Register it in global.aspx
1> Create custom Attribute
public sealed class ActionSessionStateAttribute : Attribute
{
public SessionStateBehavior SessionBehavior { get; private set; }
public ActionSessionStateAttribute(SessionStateBehavior sessionBehavior)
{
SessionBehavior = sessioBehavior;
}
}
2. Override
public class SessionControllerFactory : DefaultControllerFactory
{
protected override SessionStateBehavior GetControllerSessionBehavior(RequestContext requestContext, Type controllerType)
{
if (controllerType == null)
return SessionStateBehavior.Default;
var actionName = requestContext.RouteData.Values["action"].ToString();
Type typeOfRequest=requestContext.HttpContext.Request.RequestType.ToLower() =="get"?typeof(HttpGetAttribute):typeof(HttpPostAttribute);
// [Line1]
var cntMethods = controllerType.GetMethods()
.Where(m =>
m.Name == actionName &&
( ( typeOfRequest == typeof(HttpPostAttribute) &&
m.CustomAttributes.Where(a => a.AttributeType == typeOfRequest).Count()>0
)
||
( typeOfRequest == typeof(HttpGetAttribute) &&
m.CustomAttributes.Where(a => a.AttributeType == typeof(HttpPostAttribute)).Count() == 0
)
)
);
MethodInfo actionMethodInfo = actionMethodInfo = cntMethods != null && cntMethods.Count() == 1 ? cntMethods.ElementAt(0):null;
if (actionMethodInfo != null)
{
var sessionStateAttr = actionMethodInfo.GetCustomAttributes(typeof(ActionSessionStateAttribute), false)
.OfType<ActionSessionStateAttribute>()
.FirstOrDefault();
if (sessionStateAttr != null)
{
return sessionStateAttr.Behavior;
}
}
return base.GetControllerSessionBehavior(requestContext, controllerType);
}
3. Register class in Global.asax
public class MvcApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
// --- other code ---
ControllerBuilder.Current.SetControllerFactory(typeof(SessionControllerFactory));
}
}
Try serving the images from another domain. So something like images.mysite.com.
This will provide you two benefits: One, sessions are tracked by a cookie, so images.mysite.com won't have the cookie. Two, it will give you an additional two concurrent requests to retrieve images.
Have you considered setting up a HttpHandler to serve up your images?
SessionState attribute is quite helpful if u use mvc3. How to achieve this with mvc2 needs a little more coding.
Idea is to tell the asp.net that specific request wont use session object.
So, Create a custom route handler for specific requests
public class CustomRouteHandler : IRouteHandler
{
public System.Web.IHttpHandler GetHttpHandler(RequestContext requestContext)
{
requestContext.HttpContext.SetSessionStateBehavior(System.Web.SessionState.SessionStateBehavior.ReadOnly);
return new MvcHandler(requestContext);
}
}
SessionStateBehavior enum has 4 members, you should use "disabled" or "readonly" modes to get async behavior.
After creating this custom route handler, be sure that your specific requests goes through this handler. This can be done via defining new routes at Global.asax
routes.Add("Default", new Route(
"{controller}/{action}",
new RouteValueDictionary(new { controller = "Home", action = "Index"}),
new CustomRouteHandler()
));
Adding this route makes all your requests to be handled by your custom route handler class. You can make it specific by defining different routes.
Change DefaultCOntrollerFactory to custom ControllerFactory class. Default Controller.TempDataProvider use SessionStateTempDataProvider. you can change it.
1.Set web.config/system.web/sessionState:mode="Off".
2.create DictionaryTempDataProvider class.
public class DictionaryTempDataProvider : ITempDataProvider
{
public IDictionary<string, object> LoadTempData(ControllerContext controllerContext)
{
return new Dictionary<string, object>();
}
public void SaveTempData(ControllerContext controllerContext, IDictionary<string, object> values)
{
}
}
3.Create DictionaryTempDataControllerFactory
public class DictionaryTempDataControllerFactory : DefaultControllerFactory
{
public override IController CreateController(System.Web.Routing.RequestContext requestContext, string controllerName)
{
var controller = base.CreateController(requestContext, controllerName) as Controller;
if (controller!=null)
controller.TempDataProvider = new DictionaryTempDataProvider();
return controller;
}
}
4.In global.asax.cs Apprication_Start event set DictionaryTempDataControllerFactory.
protected void Application_Start()
{
RegisterRoutes(RouteTable.Routes);
ControllerBuilder.Current.SetControllerFactory(
new DictionaryTempDataControllerFactory()
);
}
On our server, IIS doesn't even know about sessions - it's the ASP.NET stack that handles one request per session at a time. Static files, like images, are never affected.
Is it possible that your ASP.NET app is serving the files instead of IIS?
Create new Controller
Decorate controler with [SessionState(SessionStateBehavior.Disabled)]
Refactor code you want seesion stated disabled for to that controller
I would to share my solution for disable ASP.NET Session for an specific request (in my case, a WCF Service) using an HttpModule:
public class AspNetSessionFilterModule : IHttpModule
{
public void Init(HttpApplication context)
{
context.PostMapRequestHandler += OnPostMapRequestHandler;
}
private void OnPostMapRequestHandler(object sender, EventArgs e)
{
var context = (sender as HttpApplication).Context;
DisableSessionForSomeRequests(context);
}
private void DisableSessionForSomeRequests(HttpContext context)
{
if ("~/Services/MyService.svc".Equals(context.Request.AppRelativeCurrentExecutionFilePath, StringComparison.InvariantCultureIgnoreCase))
{
context.SetSessionStateBehavior(System.Web.SessionState.SessionStateBehavior.Disabled);
}
}
public void Dispose()
{ }
}

Alternatives to System.web.ui.page

I have an ASP.Net application and I've noticed through using profilers that there is a sizable amount of processing that happens before my page even runs. In my application, we don't used viewstate, asp.Net session, and we probably don't require most of the overhead that comes of a consequence of using the asp.net page lifecycle. Is there some other class I can easily inherit from that will cut out all the Asp.Net stuff, and just let my handle writing to the page by myself?
I've heard that ASP.Net MVC can cut down page loads considerably, simply because it doesn't use the old asp.net lifecycle, and handles pages differently. Is there an easy way, maybe by simply having my web pages inherit some other class to take advantage of something like this. I would like a solution that works in ASP.Net 2.0 if at all possible.
Most articles I found where talking about using the Page as a base class and implementing functionality on top of that, it looks like you need to make your own MyPage class that implements IHttpHandler
From the MSDN article
using System.Web;
namespace HandlerExample
{
public class MyHttpHandler : IHttpHandler
{
// Override the ProcessRequest method.
public void ProcessRequest(HttpContext context)
{
context.Response.Write("This is an HttpHandler Test.");
context.Response.Write("Your Browser:");
context.Response.Write("Type: " + context.Request.Browser.Type + "");
context.Response.Write("Version: " + context.Request.Browser.Version);
}
// Override the IsReusable property.
public bool IsReusable
{
get { return true; }
}
}
}
Again, from the article: To use this handler, include the following lines in a Web.config file.
<configuration>
<system.web>
<httpHandlers>
<add verb="*" path="handler.aspx" type="HandlerExample.MyHttpHandler,HandlerTest"/>
</httpHandlers>
</system.web>
</configuration>
I'd take a look at the source code for System.web.ui.page and take a look at what it does to guide you. My guess is that it mostly just calls the different methods in the asp.net page lifecycle in the right order. You'd do something similar by calling your own page_load from the ProcessRequest method. That would route to your individual implementation of your classes that implement your MyPage.
I've never thought of doing something like this before and it sounds pretty good since I really don't use any of the bloated webforms functionality. MVC may make this whole exercise futile, but it does seem pretty neat.
My Quick Example
new base:
using System.Web;
namespace HandlerExample
{
// Replacement System.Web.UI.Page class
public abstract class MyHttpHandler : IHttpHandler
{
// Override the ProcessRequest method.
public void ProcessRequest(HttpContext context)
{
// Call any lifecycle methods that you feel like
this.MyPageStart(context);
this.MyPageEnd(context);
}
// Override the IsReusable property.
public bool IsReusable
{
get { return true; }
}
// define any lifecycle methods that you feel like
public abstract void MyPageStart(HttpContext context);
public abstract void MyPageEnd(HttpContext context);
}
Implementation for the page:
// Individual implementation, akin to Form1 / Page1
public class MyIndividualAspPage : MyHttpHandler
{
public override void MyPageStart(HttpContext context)
{
// stuff here, gets called auto-magically
}
public override void MyPageEnd(HttpContext context)
{
// stuff here, gets called auto-magically
}
}
}
If you don't need all this "asp.net stuff", you may wish to implement a custom IHttpHandler. Afaik, there are no other standard IHttpHandlers to reuse except the Page class.
To do this you should start by looking at the System.Web.UI.PageHandlerFactory class and the corresponding System.Web.IHttpHandlerFactory interface.
From there you will probably look at the System.Web.IHttpHandler inferface and the System.Web.UI.Page class.
Basically you will write your own IHttpHandlerFactory that generates IHttpHandlers that handles the page requests.

Resources