1

I am able to get the CurrentSideId, I can say anywhere through the application. I have a class called MainClass. It has static CurrentSideId property. MainClass.CurrentSiteId returns the SiteId requested.

public class MainClass{
   public static int CurrentSiteId
   {
      get { return HttpContext.Current.Request.RequestContext.RouteData.Values["CurrentSiteId"].To<int>(); }
      set {..}
   }
}

But, when it comes to ProcessRequest method of the HttpHandler, CurrentSiteId throws an exception of type System.InvalidCastException: Null object cannot be converted to a value type.

public class MyRouteHandler : MvcRouteHandler
{
    protected override IHttpHandler GetHttpHandler(RequestContext requestContext)
    {
        return new MyHttpHandler();
    }
}
public class MyHttpHandler : IHttpHandler
{
    public void ProcessRequest(HttpContext context)
    {
        var siteId = MainClass.CurrentSiteId;
    }
}

What would be the resolution?

Jude
  • 2,353
  • 10
  • 46
  • 70
  • What isn't clear about the error message? `Values` returns `null` because the key doesn't exist, hence it returns `null`, which you try to convert to an `int`. – Yuval Itzchakov Mar 10 '15 at 08:51
  • How can I get the siteid inside the HttpHandler then? – Jude Mar 10 '15 at 08:51

2 Answers2

1

You should be able to access it via context providing the route value is passed in:

Convert.ToInt16(context.Request.RequestContext.RouteData.Values["CurrentSiteId"]);

Update

Try the following:

public class MyHttpHandler : IHttpHandler
{
    public void ProcessRequest(HttpContext context)
    {
        var siteId = Convert.ToInt16(context.Request.RequestContext.RouteData.Values["CurrentSiteId"]);
    }
}
hutchonoid
  • 32,982
  • 15
  • 99
  • 104
  • I have already tried. There is no `To` extension for `Values["CurrentSiteId"]`. – Jude Mar 10 '15 at 09:36
  • @Jude I think you must either include the namespace for the extension method. If you go to definition of the `To` method you will see that or use the above. I changed it to use `Convert.ToInt16` instead. – hutchonoid Mar 10 '15 at 09:55
  • This only gives me the Controller Name and the Action Name. There seems no "CurrentSiteId" key. – Jude Mar 10 '15 at 12:26
  • @Jude The calling application must not be passing it across, what is calling it? – hutchonoid Mar 10 '15 at 12:36
  • Edited the question. Added RouteHandler. Does this answer your question? – Jude Mar 10 '15 at 13:01
  • @Jude try the update just to see if you can get it outside of the class – hutchonoid Mar 10 '15 at 13:21
0

you should check that the value is not null before casting it a good sample can be found here: In MVC3, how to get the current action name? (replace action with the method you want to call)

Community
  • 1
  • 1
Sim1
  • 534
  • 4
  • 24