Get Url of current ASP.NET Web Api 2 action

微笑、不失礼 提交于 2019-12-10 12:49:11

问题


In ASP.NET Web API 2, how can I get Url of current action. Following is illustrative example.

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

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

}

回答1:


One of the properties of the ApiController base class (from which your own controller must be derived) is called 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; }

    // ...
}

This gives you access to the HttpRequestMessage which has the following method:

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

Use the Request.RequestUri to get the URL of the current action. It will return you a Uri object that gives you access to every part of the request's URI.

Finally, you might find the following SO question useful:

  • How to get base URL in Web API controller?



回答2:


Request.RequestUri.ToString();

On MVC this can be:

Request.Url.ToString();

See also:

Request.Url.GetLeftPart(UriPartial.Authority);

and

Request.RequestUri.GetLeftPart(UriPartial.Authority);

Both will return, for example:

http://localhost:60333/




回答3:


If the question is about Web API, the answer from mLar in this thread worked like charm for me. Check this out: How to get base URL in Web API controller?



来源:https://stackoverflow.com/questions/25217765/get-url-of-current-asp-net-web-api-2-action

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!