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

查看:147
本文介绍了如何在不访问请求的情况下获取基本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完全在应用程序外部,这就是为什么仅从请求主机中提取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.

也许这将以某种方式帮助您:无需请求t,您可以使用 http:// +:5000 ) -us / aspnet / core / api / microsoft.aspnetcore.hosting.iwebhostbuilder rel = noreferrer> IWebHostBuilder 接口。它通过> code> 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);

或定义 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天全站免登陆