ASP.NET CORE - 获取API URL

问题描述 投票:0回答:4

如何获取我的 API URL(仅 API URL)。

处于开发模式

https://localhost:44372/

生产模式:

https://{{ server api url }}

这是因为我想在数据库中存储完整路径文件,如下所示:

https://localhost:44372/files/licenceFiles/1234.png
asp.net-core
4个回答
1
投票

这取决于您配置生产 URL 的位置。大约有六个地方可以开箱存放它们。

LazZiya 为您提供了一种在本地运行良好的方法,但一旦超出只有开发和生产的场景,就会遇到一些限制。

如果您在 appsettings.json 中将它们配置为环境变量,则环境变量优先。如果您的应用程序将被容器化,那么这些值中的大多数将使用环境变量来设置。

要阅读这些内容,请使用

Environment.GetEnvironmentVariable("ASPNETCORE_URLS")
,这将为您提供 Kestrel 正在侦听的内部 url。公共地址,可能会有不同的密钥 - 但你明白了。

您可以在这里阅读:https://learn.microsoft.com/en-us/aspnet/core/fundamentals/configuration/?view=aspnetcore-6.0


1
投票

appsettings.json
:

中定义两个 URL
{
    "ApiUrl_local": "https://localhost:xxx",
    "ApiUrl_web": "https://website.com";
}

然后使用

IWebHostEnvironment
检查开发模式并检索相关设置:

public class ApiConfig
{
    public IWebHostEnvironment Environment { get; }
    public IConfiguration Configuration { get; }


    public ApiConfig(IWebHostEnvironment environment, IConfiguration configuration)
    {
        Environment = environment;
        Configuration = configuration
    }

    public string ApiURL => Environment.IsDevelopment() ? 
    Configuration["ApiUrl_local"] : Configuration["ApiUrl_web"];
}

1
投票

嗯,我使用了以下内容:

    private readonly IUnitOfWork _unitOfWork;
    private readonly IHttpContextAccessor _httpAccessor;
    private string _serverPath;

    public CustomerLicenceFilesService(IUnitOfWork unitOfWork, IHttpContextAccessor httpAccessor)
    {
        _unitOfWork = unitOfWork;
        _httpAccessor = httpAccessor;
        _serverPath = $"{_httpAccessor.HttpContext.Request.Scheme}://{_httpAccessor.HttpContext.Request.Host}";
    }

0
投票

我找到了解决方案

$“{Request.Scheme}://{Request.Host}{Request.PathBase}{Request.Path}{Request.QueryString}”

答案归功于 Niels Swimberghe,可以在 https://swimburger.net/blog/dotnet/how-to-get-the-full-public-url-of-aspdotnet-core

© www.soinside.com 2019 - 2024. All rights reserved.