How use UrlHelper in signalR HubClass

眉间皱痕 提交于 2019-12-10 13:58:20

问题


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.


回答1:


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);
    }
}



回答2:


You can do it with this, and I am using T4MVC.

var urlHelper = new UrlHelper(Context.Request.GetHttpContext().Request.RequestContext);
var url = urlHelper.Action(MVC.Directors.EventSchedule.Index(EventId));


来源:https://stackoverflow.com/questions/16566692/how-use-urlhelper-in-signalr-hubclass

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!