How to get base URL in Web API controller?

web api get client url
net core web api get base url
web api get current route
asp.net core get base url
.net web api get request url
asp.net core get base url startup
mvc get base url
asp.net core 2.0 get current url

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?

You could use VirtualPathRoot property from HttpRequestContext (request.GetRequestContext().VirtualPathRoot)

asp.net web api How to get base URL in Web API controller?, Url.Link("DefaultApi", new { controller = "Person", id = person.Id }). This is the official way which does not require any helper or workaround. If you look at this  This route has an api path segment. Thus your second url will not match default api route; This route does not have action parameter. That's because actions of ApiControllers are mapped by HTTP method of the request. You should not specify action name in request url. By convention, for HTTP GET requests name of action should begin with Get word.

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

How to Get the Base URL in ASP.NET, NET Standard with MVC and with .NET Core and dependency injection. How to Get the Base URL in an MVC Controller. Here's a simple one-  Action method name can be the same as HTTP verbs like Get, Post, Put, Patch or Delete as shown in the Web API Controller example above. However, you can append any suffix with HTTP verbs for more readability. For example, Get method can be GetAllNames (), GetStudents () or any other name which starts with Get.

Url.Content("~/")

worked for me!

Get URL of requesting website in WEB API 2, I need to get URL of requesting web site in My WEB API 2. I need to do this At your WebAPI controller actions, you can use the following code to get requesting website urls. ToString(); //string baseUrl = Url.Request. You can get the base Url(https://qawithexperts.com) in C# using the code below Continuing the above code, you can get absolute URL(or you can say after base URL, ie. like /questions/111/invalid-uri-the-format-of-the-uri-could-not-be-determined-er) using the code below

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));

MVC - how to get complete url and base url in MVC?, How can I get complete and base type of URL in C# asp.net MVC web-​application, controller, for example, if my web-application URL is  First you get full URL using HttpContext.Current.Request.Url.ToString(); then replace your method url using Replace("user/login", ""). 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.

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

}

HttpRequest.Url Property (System.Web), Gets information about the URL of the current request. public: property Uri ^ Url { Uri ^ get(); };. C# Copy. The reason for using "api" in the route is to avoid collisions with ASP.NET MVC routing. That way, you can have "/contacts" go to an MVC controller, and "/api/contacts" go to a Web API controller. Of course, if you don't like this convention, you can change the default route table. Once a matching route is found, Web API selects the controller

Routing in ASP.NET Web API, That way, you can have "/contacts" go to an MVC controller, and "/api/contacts" go to a Web API controller. Of course, if you don't like this  Creates a new web API project and opens it in Visual Studio Code. Adds the NuGet packages which are required in the next section. Select File > New Solution. Select .NET Core > App > API > Next. In the Configure your new ASP.NET Core Web API dialog, select Target Framework of *.NET Core 3.1. Enter TodoApi for the Project Name and then select Create.

Getting the base URL for an ASP.NET Core MVC web application in , 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​  Don't create a web API controller by deriving from the Controller class. Controller derives from ControllerBase and adds support for views, so it's for handling web pages, not web API requests. There's an exception to this rule: if you plan to use the same controller for both views and web APIs, derive it from Controller .

Building RESTful API with ASP.NET Core @ http://jojozhuang.github.io, In this post I want to show a simple way for getting the base URL for an ASP.NET Core MVC web application in your static JavaScript files. How to manage request and response in Web API: See the image below - In this image, you can see, if you are using Authorization filter, it will apply according to your logic. In this case, I am going to create a logic to check any HTTP and HTTPS request inside AuthorizationfilterAttribute class.

Comments
  • Request.GetRequestContext().VirtualPathRoot returns /. I self-host Web API on localhost in Windows service using Owin. Any way to get base URL in this case? Thank you.
  • Hmm..this should return the correct virtual path. I tried it myself now and it works fine. Could you share how you are setting the virtual path (for example, I do like this: using (WebApp.Start<Program>("http://localhost:9095/Test")) where VirtualPathRoot returns /Test)
  • Ok, this makes sense. I set http://localhost:5550/ and it correctly returns /. What I meant is how to get http://localhost:5550/ in this case...
  • Ok, since you have access to the HttpRequestMessage(Request.RequestUri), you could grab the request uri of it and find the scheme,host and port...right?
  • new Uri(Request.RequestUri, RequestContext.VirtualPathRoot)
  • This is incorrect, it only happens to work if you're running your site as the root site in IIS. If you're running your application within another application, i.e. localhost:85458/Subfolder/api/ctrl then this would yield the wrong answer (it wouldn't include "/Subfolder" which it should).
  • I came here for this anwser :)
  • Works on .Net Core 2.2
  • And how do you inject HttpRequestMessage?
  • @RichardSzalay Autofac has it built in, github.com/autofac/Autofac/blob/master/Core/Source/… but the general idea is you setup a DI container and then use a message handler to grab the HttpRequestMessage and register it in a per-request handler.