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

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

问题描述

说我的网站托管在 www.example.com mywebsite 文件夹中,而我访问

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

如何在MVC控制器中获取基本网址部分?我要查找的部分是 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中获取网站的基本URL?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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