如何在不访问请求的情况下获取基本 URL [英] How to get base url without accessing a request

查看:16
本文介绍了如何在不访问请求的情况下获取基本 URL的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在没有请求的情况下获取 AspNet 核心应用程序中的基本 URL?

How to get the base URL in AspNet core application without having a request?

我从请求中知道您可以获得方案和主机(即 $"{Request.Scheme}://{Request.Host}" 会给出类似 https://localhost:5000),但是是否可以从其他任何地方获取此信息?

I know from the Request you can get the scheme and host (ie $"{Request.Scheme}://{Request.Host}" would give something like https://localhost:5000), but is it possible to get this information from anywhere else?

也就是说,如果我有一个需要构建绝对 URL 的服务类,在没有可用的 http 请求的情况下,如何获取当前 URL?

In other words, if I have a service class that needs to build absolute URLs, how can I get the current URL when there is not an http request available?

更新:也许这种情况甚至没有意义,因为托管 URL 完全在应用程序外部,这就是为什么只有从请求主机中提取它才有意义..

UPDATE: Maybe that scenario does not even make sense since the hosting URL is totally external to the application and that's why it only makes sense to extract it from the Request host..

推荐答案

你是对的,托管 URL 是一个外部信息,你可以简单地将它作为配置参数传递给你的应用程序.

You are right, hosting URL is an external information, and you can simply pass it as configuration parameter to your application.

也许这会对您有所帮助:无需请求,您就可以使用 IWebHostBuilder 接口.它通过 GetSetting 方法:

Maybe this will help you somehow: without request, you can get a configured listening address (like http://+:5000) using the IWebHostBuilder interface. It provides access to host settings via the GetSetting method:

/// <summary>
/// Get the setting value from the configuration.
/// </summary>
/// <param name="key">The key of the setting to look up.</param>
/// <returns>The value the setting currently contains.</returns>
string GetSetting(string key);

有一个 WebHostDefaults.ServerUrlsKey 设置名称,允许配置监听地址.我们在添加 .UseUrls 扩展方法时覆盖它:

There is a WebHostDefaults.ServerUrlsKey setting name, that allows to configure listening address. We override it when add .UseUrls extension method:

public static IWebHostBuilder UseUrls(this IWebHostBuilder hostBuilder, params string[] urls);

或定义 文档(你知道,默认监听配置为localhost:5000).

or define urls configuration parameter as described in the documentation (you know, by default listening is configured to localhost:5000).

因此,拥有 IWebHostBuilder 的实例,您可以调用 .GetSetting(WebHostDefaults.ServerUrlsKey) 并获取当前值.

So, having instance of IWebHostBuilder, you can call .GetSetting(WebHostDefaults.ServerUrlsKey) and get the current value.

这篇关于如何在不访问请求的情况下获取基本 URL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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