如何在signalR HubClass中使用UrlHelper [英] How use UrlHelper in signalR HubClass
问题描述
我有一个由Hub驱动的Chat类. 我想知道是否有一种通过URLHelper构建URL的方法,例如:Url.Action("action","Controller").
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").
因为我可以从2个抽象类(集线器,控制器)派生该类,所以我不知道是否有其他方法来构建完整的URls而不是Hard代码.
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.
推荐答案
我目前在我的Hub中使用此代码,我敢肯定有更好的方法来做到这一点,但这是可行的.
I use this code in my Hub currently, I'm sure there is a better way to do this, but this works.
注意:如果要使用完全限定的网址,请确保正确设置了域(example.com).
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);
}
}
这篇关于如何在signalR HubClass中使用UrlHelper的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!