请注意,本站并不支持低于IE8的浏览器,为了获得最佳效果,请下载最新的浏览器,推荐下载 Chrome浏览器
欢迎光临。交流群:166852192

Cleanly getting a WebAPI action URL


Whenever you need to get the URL of a ASP.NET MVC action, you should use Url.Action (where URL is an instance of UrlHelper), and never hard-code the URL. This way, the URL is dynamically constructed from the available information in the Url.Action parameters and in the route table. If the route is changed, the results of the Url.Action call will change accordingly, and everything will continue to work. The same principles, of course, apply to WebAPI actions.
In Orchard, when you need a MVC UrlHelper, you can just inject it: there is special logic in Orchard.Mvc.MvcModule that can create a UrlHelper instance in almost any situation, including complex cases where the code is running in a background process that has no HttpContext. The equivalent code for WebAPI’s UrlHelper unfortunately doesn’t exist. Building it would be non-trivial, a difficulty being in particular to build or acquire the HttpRequestMessage instance that it needs, outside of a WebAPI controller.
Fortunately, we don’t need to do that. There’s a simpler way, which is simply to use the ASP.NET MVC UrlHelper, which will work just fine on WebAPI actions, even though the routes are in a different table, if you specify the httproute parameter in your route values:
var actionUrl = _url.Action(, ,  {
    httproute = ,
    area = 
});
This will get the WebAPI controller ImportController’s Content action’s URL (from the Orchard.ImportExport module), using only the MVC UrlHelper.



作者原创内容不容易,如果觉得内容不错,请点击右侧“打赏”,赏俩给作者花花,也算是对作者付出的肯定,也可以鼓励作者原创更多更好内容。
更多详情欢迎到QQ群 166852192 交流。