8

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

}

2 Answers 2

16

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:

Sign up to request clarification or add additional context in comments.

Comments

4

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/

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.