如何在 ASP.NET Core 中获取我网站的 baseurl? [英] How can I get the baseurl of my site in ASP.NET Core?

查看:30
本文介绍了如何在 ASP.NET Core 中获取我网站的 baseurl?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Say my website is hosted in the mywebsite folder of www.example.com and I visit https://www.example.com/mywebsite/home/about.

如何在 MVC 控制器中获取基本 url 部分?我正在寻找的部分是 https://www.example.com/mywebsite

How do I get the base url part in an MVC controller? The part that I am looking for is https://www.example.com/mywebsite

此处列出的示例 不起作用,因为我们无权访问 ASP.NET Core 中的 Request.Url

The example listed here doesn't work as we don't have access to Request.Url in ASP.NET Core

推荐答案

你应该仍然能够拼凑你需要的东西.如果您的控制器继承自 Controller,则您可以访问请求对象.

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

如果您使用的是 VS2017,请启动一个新的 ASPNet Core MVC 应用并将 homecontroller 替换为:

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

我只是在About"方法中添加了一些您可能感兴趣的内容,但您应该探索请求类的其余部分,以便了解还有什么可用的.

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.

正如@Tseng 指出的那样,在 IIS 或 Azure App Service 后面运行 Kestrel 时可能会遇到问题,但如果您使用 IISIntegration 包或 AzureAppServices 包(通过安装 Nuget 包并将其添加到 Program.cs 到 WebHostBuilder),它应该将这些标题转发给您.它在 Azure 中非常适合我,因为我有时必须根据他们命中的主机名做出决定.IIS/Azure 包还转发我记录的原始远程 IP 地址.

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.

这篇关于如何在 ASP.NET Core 中获取我网站的 baseurl?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆