How do I Access the RequestContext Outside the Controller?

nfplee picture nfplee · Sep 16, 2010 · Viewed 23.8k times · Source

Background

I am trying to move business logic out from the controllers into their own services.

Controller

public class AccountController : Controller
{
    private readonly IAccountService _accountService; 

    public AccountController(IAccountService accountService)
    {
        _accountService = accountService;
    }

    ....
}

I'm using Unity to inject dependencies. I'd like to use the Url.GenerateUrl() helper method within the implementation of IAccountService but Url is a property against the controller.

I looked at the MVC source to see how this is done but it requires me to access the RequestContext from outside of the controller, and I don't know how to do that.

Question

How do I access the RequestContext from outside the controller? If that won't solve my problem, how do I solve the problem given my setup?

Answer

LukeH picture LukeH · Sep 16, 2010

This might not be quite right because I'm unable to test it at the moment, but I think that you can do something like this in .NET 4+:

using System.Web;
using System.Web.Mvc;

// ...

var helper = new UrlHelper(HttpContext.Current.Request.RequestContext);
string url = helper.GenerateUrl(/* ... */);

It might make more sense to pass the context from the controller to your IAccountService implementation rather than grabbing it directly from HttpContext.Current.