如何在 ASP.NET 核心中获取站点的 baseurl?

假设我的网站托管在 Www.example.com我的网站文件夹中,我访问 https://www.example.com/mywebsite/home/about

如何在 MVC 控制器中获得基 URL 部分?我要找的零件是 翻译: 奇芳翻译: 奇芳翻译: 奇芳翻译: 奇芳翻译: 奇芳翻译: 奇芳翻译: 奇芳翻译: 奇芳翻译: 奇芳翻译: 奇芳翻译: 奇芳翻译: 奇芳翻译: 奇芳翻译: 奇芳 https://www.example.com/mywebsite

列出的示例 给你不起作用,因为我们无法访问 ASP.NET 核心中的 Request.Url

138107 次浏览

You should still be able to piece together what you need. You have access to the request object if your controller inherits from Controller.

If you are using VS2017, fire up a new ASPNet Core MVC app and replace the homecontroller with:

public class HomeController : Controller
{
public IActionResult Index()
{
return View();
}


public IActionResult About()
{
ViewData["Message"] = $"{this.Request.Scheme}://{this.Request.Host}{this.Request.PathBase}";


return View();
}


public IActionResult Contact()
{
ViewData["Message"] = "Your contact page.";


return View();
}


public IActionResult Error()
{
return View();
}
}

I just put in some of the stuff that might interest you in the "About" method, but you should explore the rest of the request class so you know what else is available.

As @Tseng pointed out, you might have a problem when running Kestrel behind IIS or Azure App Service, but if you use the IISIntegration package or AzureAppServices package (by installing the Nuget package and adding it in Program.cs to your WebHostBuilder), it should forward those headers to you. It works great for me in Azure, because I sometimes have to make decisions based on which hostname they hit. The IIS/Azure packages also forward the original remote IP address, which I log.

If you need this anywhere in your app than you should create a class and add it as a service. Define your static class and your extension method for adding it to the service pipeline like this.

public class MyHttpContext
{
private static IHttpContextAccessor m_httpContextAccessor;


public static HttpContext Current => m_httpContextAccessor.HttpContext;


public static string AppBaseUrl => $"{Current.Request.Scheme}://{Current.Request.Host}{Current.Request.PathBase}";
    

internal static void Configure(IHttpContextAccessor contextAccessor)
{
m_httpContextAccessor = contextAccessor;
}
}


public static class HttpContextExtensions
{
public static void AddHttpContextAccessor(this IServiceCollection services)
{
services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
}


public static IApplicationBuilder UseHttpContext(this IApplicationBuilder app)
{
MyHttpContext.Configure(app.ApplicationServices.GetRequiredService<IHttpContextAccessor>());
return app;
}
}

It might be a little redundant to expose the HttpContext in this case but I find it very helpful.

You would than add it to the pipeline in your Configfure method which is located in Startup.cs

app.UseHttpContext()

From there it is simple to use it anywhere in your code.

var appBaseUrl = MyHttpContext.AppBaseUrl;
string.Format("{0}://{1}{2}", Request.Url.Scheme, Request.Url.Authority, Url.Content("~"));

you can check for more information here: How can I get my webapp's base URL in ASP.NET MVC?

NPNelson answer works if with .Value.ToString()

var baseUrl = $"{this.Request.Scheme}://{this.Request.Host.Value.ToString()}{this.Request.PathBase.Value.ToString()}";
var baseUrl = Request.GetTypedHeaders().Referer.ToString();

This way you can capture the base url information.

This is how I could get it in Asp .Net Core 3.1 version.

You can access the resource from the link below.

Reference

using Microsoft.AspNetCore.Http;


public void ConfigureServices(IServiceCollection services)
{
services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
}
    

    

public AccountController(IHttpContextAccessor httpContextAccessor)
{
var request = httpContextAccessor.HttpContext.Request;
var domain = $"{request.Scheme}://{request.Host}";
//domain => https://varunsoft.in
}

All of these existing answers depend on an HttpContext object, which is only available during an incoming request. However, I needed to get the URLs in a background service where HttpContext was not available.

This information is also available in the Microsoft.AspNetCore.Hosting.Server.IServer service, as long as the actual host service provides this information. If you're using the default Kestrel server, I've found that it is indeed provided. I have not tested this when hosting IIS in-process or with other hosting models.

You need to get an instance of IServer and then look for the .Features entry of type IServerAddressesFeature. Here's an extension method to get the URL(s) directly from an IServiceProvider:

using Microsoft.AspNetCore.Hosting.Server;
using Microsoft.AspNetCore.Hosting.Server.Features;


public static ICollection<string> GetApplicationUrls(this IServiceProvider services)
{
var server = services.GetService<IServer>();


var addresses = server?.Features.Get<IServerAddressesFeature>();


return addresses?.Addresses ?? Array.Empty<string>();
}

You could however accomplish the same thing by injecting IServer if DI services are available.