如何从ASP.net WebApi 2中控制器外部的帮助器方法生成指向控制器动作的URL?
return new UrlHelper().Link("Default", new
{
Controller = "MyController",
Action = "MyAction"
});
更新
在WebApi中生成URL与ASP.net MVC不同
答案 0 :(得分:2)
这是我克服这个问题的方式:
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{action}",
defaults: new { id = RouteParameter.Optional }
);
public static string GenerateLink(HttpRequestMessage httpRequest)
{
var urlHelper = new UrlHelper(httpRequest).Route("DefaultApi", new
{
Controller = "MyController",
Action = "MyAction"
});
return httpRequest.RequestUri.Scheme + "://" + httpRequest.RequestUri.Authority + urlHelper;
}
最后调用辅助类的api controller
:
public class DefaultController : ApiController
{
[HttpGet]
public string Default()
{
var link = HelperClass.GenerateLink(Request);
return link;
}
}