[url] How to get base URL in Web API controller?

I know that I can use Url.Link() to get URL of a specific route, but how can I get Web API base URL in Web API controller?

This question is related to url asp.net-web-api base-url asp.net-web-api2

The answer is


Url.Content("~/")

worked for me!


send a GET to a page and the content replied will be the answer.Base url : http://website/api/


First you get full URL using HttpContext.Current.Request.Url.ToString(); then replace your method url using Replace("user/login", "").

Full code will be

string host = HttpContext.Current.Request.Url.ToString().Replace("user/login", "")

Al WebApi 2, just calling HttpContext.Current.Request.Path;


Not sure if this is a Web API 2 addition, but RequestContext has a Url property which is a UrlHelper: HttpRequestContext Properties. It has Link and Content methods. Details here


new Uri(Request.RequestUri, RequestContext.VirtualPathRoot)

I inject this service into my controllers.

 public class LinkFactory : ILinkFactory
 {
    private readonly HttpRequestMessage _requestMessage;
    private readonly string _virtualPathRoot;


    public LinkFactory(HttpRequestMessage requestMessage)
    {
        _requestMessage = requestMessage;
        var configuration = _requestMessage.Properties[HttpPropertyKeys.HttpConfigurationKey] as HttpConfiguration;
        _virtualPathRoot = configuration.VirtualPathRoot;
        if (!_virtualPathRoot.EndsWith("/"))
        {
            _virtualPathRoot += "/";
        }
    }

    public Uri ResolveApplicationUri(Uri relativeUri)
    {

        return new Uri(new Uri(new Uri(_requestMessage.RequestUri.GetLeftPart(UriPartial.Authority)), _virtualPathRoot), relativeUri);
    }

}

This is what I use:

Uri baseUri = new Uri(Request.RequestUri.AbsoluteUri.Replace(Request.RequestUri.PathAndQuery, String.Empty));

Then when I combine it with another relative path, I use the following:

string resourceRelative = "~/images/myImage.jpg";
Uri resourceFullPath = new Uri(baseUri, VirtualPathUtility.ToAbsolute(resourceRelative));

In ASP.NET Core ApiController the Request property is only the message. But there is still Context.Request where you can get expected info. Personally I use this extension method:

public static string GetBaseUrl(this HttpRequest request)
{
    // SSL offloading
    var scheme = request.Host.Host.Contains("localhost") ? request.Scheme : "https";
    return $"{scheme}://{request.Host}{request.PathBase}";
}

In .NET Core WebAPI (version 3.0 and above):

var requestUrl = $"{Request.Scheme}://{Request.Host.Value}/";


     

Use the following snippet from the Url helper class

Url.Link("DefaultApi", new { controller = "Person", id = person.Id })

The full article is available here: http://blogs.msdn.com/b/roncain/archive/2012/07/17/using-the-asp-net-web-api-urlhelper.aspx

This is the official way which does not require any helper or workaround. If you look at this approach is like ASP.NET MVC


Base on Athadu's answer, I write an extenesion method, then in the Controller Class you can get root url by this.RootUrl();

public static class ControllerHelper
{
    public static string RootUrl(this ApiController controller)
    {
        return controller.Url.Content("~/");
    }
}

  1. Add a reference to System.Web using System.Web;

  2. Get the host or any other component of the url you want string host = HttpContext.Current.Request.Url.Host;


From HttpRequestMessage

request.Headers.Host

In the action method of the request to the url "http://localhost:85458/api/ctrl/"

var baseUrl = Request.RequestUri.GetLeftPart(UriPartial.Authority) ;

this will get you http://localhost:85458


Examples related to url

What is the difference between URL parameters and query strings? Allow Access-Control-Allow-Origin header using HTML5 fetch API File URL "Not allowed to load local resource" in the Internet Browser Slack URL to open a channel from browser Getting absolute URLs using ASP.NET Core How do I load an HTTP URL with App Transport Security enabled in iOS 9? Adding form action in html in laravel React-router urls don't work when refreshing or writing manually URL for public Amazon S3 bucket How can I append a query parameter to an existing URL?

Examples related to asp.net-web-api

Entity Framework Core: A second operation started on this context before a previous operation completed FromBody string parameter is giving null How to read request body in an asp.net core webapi controller? JWT authentication for ASP.NET Web API Token based authentication in Web API without any user interface Web API optional parameters How do I get the raw request body from the Request.Content object using .net 4 api endpoint How to use a client certificate to authenticate and authorize in a Web API HTTP 415 unsupported media type error when calling Web API 2 endpoint The CodeDom provider type "Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider" could not be located

Examples related to base-url

Laravel: Get base url How to get base URL in Web API controller? How get the base URL via context path in JSF? Getting the base url of the website and globally passing it to twig in Symfony 2 How to get domain URL and application name?

Examples related to asp.net-web-api2

CORS: credentials mode is 'include' FromBody string parameter is giving null Web API optional parameters HTTP 415 unsupported media type error when calling Web API 2 endpoint Asp.Net WebApi2 Enable CORS not working with AspNet.WebApi.Cors 5.2.3 How to implement oauth2 server in ASP.NET MVC 5 and WEB API 2 Pass multiple complex objects to a post/put Web API method Where can I find a NuGet package for upgrading to System.Web.Http v5.0.0.0? How to get base URL in Web API controller? No connection could be made because the target machine actively refused it?