0

I've got the following code (lifted from here), and I'm trying to run it on a linux server w/ mono 2.10.5.

private static HttpContext GetCurrentContext(ControllerContext context) {
    var currentApplication = (HttpApplication)context.HttpContext.GetService(typeof(HttpApplication));
    if (currentApplication == null) {
        throw new NullReferenceException("currentApplication");
    }

    return currentApplication.Context;
}

When running on mono, I get the following exception, which is straightforward enough:

System.NotImplementedException: The requested feature is not
implemented.   at System.Web.HttpContextWrapper.GetService
(System.Type serviceType) [0x00000] in <filename unknown>:0

Is there a known workaround I can use to accomplish the same result on mono?

AlexCuse
  • 17,378
  • 5
  • 38
  • 51

1 Answers1

3

Not sure about the GetService method in Mono but the code you have lifted could be shortened like this:

private static HttpContextBase GetCurrentContext(ControllerContext context) {
    return context.HttpContext;
}

You don't really need to go through the Application in order to fetch the HttpContext when you have direct access to it. I have also changed the return type to HttpContextBase instead of HttpContext because in ASP.NET MVC it is recommended to always work with abstractions. It makes your code more weakly coupled and unit testable.

Or if for some unknown to me reason you want to work with an actual HttpContext (no idea why someone would like to tie his code to it) you could try the following:

private static HttpContext GetCurrentContext(ControllerContext context) {
    return context.HttpContext.ApplicationInstance.Context;
}

But as you can see in both cases the existence of this GetCurrentContext static method becomes quite questionable.

Darin Dimitrov
  • 960,118
  • 257
  • 3,196
  • 2,876
  • Lifted, nicked, etc... - all sound better than stolen right ;) You got me halfway there - GetService is being used to convert HttpContextBase to an HttpContext (as required by ELMAH). From the comments on this post (http://stackoverflow.com/a/4567707/794) it appears that context.HttpContext.ApplicationInstance.Context will do the trick (and work on mono). If you want to edit your answer, I will accept it. – AlexCuse Feb 11 '12 at 21:21