Pavan Kumar
Pavan Kumar

Reputation: 1881

Get Url of current ASP.NET Web Api 2 action

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*/
    ....

}

Upvotes: 8

Views: 24643

Answers (3)

bbsimonbb
bbsimonbb

Reputation: 28992

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/

Upvotes: 4

Elek Guidolin
Elek Guidolin

Reputation: 527

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?

Upvotes: 0

djikay
djikay

Reputation: 10628

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:

Upvotes: 16

Related Questions