views:

42

answers:

2

I need to build a URL for self-ping action. I want to initialize that URL from Application_Start, which doesn't have HttpContext (on ISS 7.0 integrated mode).

I have code to build absolute Action URL using HttpContext, now I need the same but use HttpRuntime instead.

+1  A: 
using System;
using System.IO;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;

class Program
{
    static void Main()
    {
        RouteTable.Routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

        RouteTable.Routes.MapRoute(
            "Default",
            "{controller}/{action}/{id}",
            new { controller = "Home", action = "Index", id = UrlParameter.Optional }
        );

        var request = new HttpRequest("/", "http://foo.com", "");
        var response = new HttpResponse(new StringWriter());
        var httpContext = new HttpContext(request, response);
        var httpContextBase = new HttpContextWrapper(httpContext);
        var routeData = new RouteData();
        var requestContext = new RequestContext(httpContextBase, routeData);
        var urlHelper = new UrlHelper(requestContext, RouteTable.Routes);

        var url = urlHelper.Action("Index", "Home", new { id = "123" }, "http");
        Console.WriteLine(url);
    }
}
Darin Dimitrov
+1  A: 

The following worked for me. It may not be the most eloquent way to create action URL's without a request, but it works. Improvements are welcome.

// Create an MVC UrlHelper to create our URL.
// Feed it with a mock RequestContext
UrlHelper urlHelper = new UrlHelper(
    new RequestContext(
        new HttpContextWrapper(
            new HttpContext(
                new HttpRequest("", "http://a.com", ""), // this can be any domain name -- it's not used in creating the URL
                new HttpResponse(new StringWriter()))),
        new RouteData()));

// UrlHelper creates a relative URL -- make sure to root it at our domain
Uri myNewUri = new Uri(
    new Uri("http://mydomain.com"),
    urlHelper.Action("myAction", "myController"));
Oren Trutner