如何在ASP.NET WebApi 2中的控制器外部生成URL?

时间:2019-05-08 05:20:02

标签: c# asp.net-web-api2

如何从ASP.net WebApi 2中控制器外部的帮助器方法生成指向控制器动作的URL?

return new UrlHelper().Link("Default", new
{
    Controller = "MyController",
    Action = "MyAction"
});

更新
在WebApi中生成URL与ASP.net MVC不同

1 个答案:

答案 0 :(得分:2)

这是我克服这个问题的方式:

RouteConfig

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;
    }
}