获取当前ASP.NET Web Api 2操作的URL

Pav*_*mar 8 asp.net asp.net-web-api2

在ASP.NET Web API 2中,如何获取当前操作的Url.以下是说明性示例.

[HttpGet]
[Route("api/someAction")]
public SomeResults GetAll()
{

    var url = /* what to write here*/
    ....

}
Run Code Online (Sandbox Code Playgroud)

dji*_*kay 14

ApiController调用基类的一个属性(必须从中派生自己的控制器)Request:

// Summary:
//     Defines properties and methods for API controller.
public abstract class ApiController : IHttpController, IDisposable
{
    // ...

    //
    // Summary:
    //     Gets or sets the HttpRequestMessage of the current System.Web.Http.ApiController.
    //
    // Returns:
    //     The HttpRequestMessage of the current System.Web.Http.ApiController.
    public HttpRequestMessage Request { get; set; }

    // ...
}
Run Code Online (Sandbox Code Playgroud)

这使您可以访问HttpRequestMessage具有以下方法的方法:

//
// Summary:
//     Gets or sets the System.Uri used for the HTTP request.
//
// Returns:
//     Returns System.Uri.The System.Uri used for the HTTP request.
public Uri RequestUri { get; set; }
Run Code Online (Sandbox Code Playgroud)

使用它Request.RequestUri来获取当前操作的URL.它将返回一个Uri对象,使您可以访问请求的URI的每个部分.

最后,您可能会发现以下SO问题很有用: