Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How use UrlHelper in signalR HubClass

I have a Chat class drived from Hub. I want to know if thers a way to built URL by URLHelper like : Url.Action("action","Controller").

as i can derived the class from 2 abstract classes (Hub, Controller) i dont know if thers other way to build complete URls and not Hard code.

like image 393
Ross Cyrus Avatar asked May 15 '13 13:05

Ross Cyrus


1 Answers

I use this code in my Hub currently, I'm sure there is a better way to do this, but this works.

Note: If you want a a fully qualified url, make sure you set the domain correctly (example.com).

protected virtual UrlHelper Url
{
    get
    {
        var httpContext = HttpContext.Current;

        if (httpContext == null)
        {
            var request = new HttpRequest("/", "http://example.com", "");
            var response = new HttpResponse(new StringWriter());
            httpContext = new HttpContext(request, response);
        }

        var httpContextBase = new HttpContextWrapper(httpContext);
        var routeData = new RouteData();
        var requestContext = new RequestContext(httpContextBase, routeData);

        return new UrlHelper(requestContext);
    }
}
like image 108
Khalid Abuhakmeh Avatar answered Sep 21 '22 15:09

Khalid Abuhakmeh