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*/
....
}
You can easily find the Web API addresses and version number for your deployment in the Customer Engagement web application by navigating to Settings > Customization > Developer Resources.
The [FromBody] attribute which inherits ParameterBindingAttribute class is used to populate a parameter and its properties from the body of an HTTP request. The ASP.NET runtime delegates the responsibility of reading the body to an input formatter.
ActionName attribute is an action selector which is used for a different name of the action method. We use ActionName attribute when we want that action method to be called with a different name instead of the actual name of the method.
routes.MapHttpRoute( name: "ActionApi", routeTemplate: "api/{controller}/{action}/{id}", defaults: new { id = RouteParameter.Optional } ); In this route template, the {action} parameter names the action method on the controller. With this style of routing, use attributes to specify the allowed HTTP verbs.
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:
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/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With