如何在 ASP.NET WebApi 2 中的控制器外部生成 URL?
How do I generate a URL outside of a controller in ASP.NET WebApi 2?
如何在 ASP.net WebApi 2 中从控制器外部的辅助方法生成指向控制器操作的 URL?
return new UrlHelper().Link("DefaultApi", new
{
Controller = "MyController",
Action = "MyAction"
});
更新 1
在 WebApi 中生成 URL 不同于 ASP.net MVC
更新 2
这是路由配置:
config.Routes.MapHttpRoute(
"DefaultApi",
"API/{Controller}/{Action}"
);
我是这样克服的:
路由配置
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{action}",
defaults: new { id = RouteParameter.Optional }
);
帮手Class
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
调用助手 class:
public class DefaultController : ApiController
{
[HttpGet]
public string Default()
{
var link = HelperClass.GenerateLink(Request);
return link;
}
}
如何在 ASP.net WebApi 2 中从控制器外部的辅助方法生成指向控制器操作的 URL?
return new UrlHelper().Link("DefaultApi", new
{
Controller = "MyController",
Action = "MyAction"
});
更新 1
在 WebApi 中生成 URL 不同于 ASP.net MVC
更新 2
这是路由配置:
config.Routes.MapHttpRoute(
"DefaultApi",
"API/{Controller}/{Action}"
);
我是这样克服的:
路由配置
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{action}",
defaults: new { id = RouteParameter.Optional }
);
帮手Class
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
调用助手 class:
public class DefaultController : ApiController
{
[HttpGet]
public string Default()
{
var link = HelperClass.GenerateLink(Request);
return link;
}
}