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("Content", "Import", new {
httproute = true,
area = "Orchard.ImportExport"
});
This will get the WebAPI controller ImportController’s Content action’s URL (from the Orchard.ImportExport module), using only the MVC UrlHelper.