【问题标题】:Null WebRootPath in ConfigureServices for Blazor Hosted托管 Blazor 的 ConfigureServices 中的空 WebRootPath
【发布时间】:2020-07-09 03:25:59
【问题描述】:

我想在 Blazor 托管解决方案中从 Blazor.Server.Startup.ConfigureServices 访问 Web 根路径。

我已将IWebHostEnvironment 注入Startup 构造函数并将其保存为名为“WebHostEnvironment”的属性。问题是在 ConfigureServices 中,WebHostEnvironment.WebRootPath 始终为空。

我已经验证过:

  • wwwroot 文件夹存在于我的 Blazor.Client 项目中。
  • app.UseStaticFiles(); 已在 Startup.Configure 中调用(不确定这是否有必要,但这是我找到的少数推荐解决方案之一)。

这似乎是一个常见问题(也许 WebRootPath 仅在某些条件下填充 - 例如在我的应用程序发布/部署之后?),但是我无法在任何地方找到明确、明确的答案,我不知道我能做些什么来获取ConfigureServices 中的网络根路径。

用例

虽然与问题没有直接关系,但我正在尝试获取令牌端点的路径,以便我可以在新的 OpenApiAuthFlow 中为 Swashbuckle 的 AddSwaggerGen 服务配置 TokenUrl 属性。我宁愿不必指定 localhost URL,因为它最终将部署到生产网站。我想如果需要我可以将它存储在 appsettings 中,但我希望不必在那里维护路径。

services.AddSwaggerGen(options =>
    {
        options.SwaggerDoc("v1", new OpenApiInfo {Title = "Protected API", Version = "v1"});
        options.AddSecurityDefinition("oauth2", new OpenApiSecurityScheme
        {
            Type = SecuritySchemeType.OAuth2,
            Flows = new OpenApiOAuthFlows
            {
                AuthorizationCode = new OpenApiOAuthFlow
                {
                    AuthorizationUrl = new Uri("https://localhost:5000/connect/authorize"),
                    TokenUrl = new Uri("https://localhost:5000/connect/token"),
                    Scopes = new Dictionary<string, string>
                    {
                        {"api1", "Demo API - full access"}
                    }
                }
            }
        });
    });

【问题讨论】:

  • 好的,谢谢。如果在ConfigureServices中无法获取WebRootPath,我会通过从配置中加载路径来做类似的事情。
  • 我不这么认为,但是您实际上要加载哪个配置文件?如果您尝试从服务器端加载客户端配置文件,这是可能的,但需要更多代码。

标签: c# asp.net-core blazor


【解决方案1】:

这不是一个错误,而是一个特性;你只是不能在ConfigureServices中做你想做的事。
如果您想访问 wwwroot 文件夹,请将代码放入 Configure 方法或 ServiceCollection 方法中,您可以获得 IServiceProvider 实例,例如 .AddTransient

样本

services.AddTransient(p =>
{
    var environment = p.GetRequiredService<IWebHostEnvironment>();
    var path = environment.WebRootPath;
    return new Stuff(path);
});

【讨论】:

  • 您提到它应该可以从Configure 访问,但是当我将IWebHostEnvironment 注入Startup.Configure 时,WebRootPath 仍然为空。
猜你喜欢
  • 1970-01-01
  • 2019-07-02
  • 1970-01-01
  • 1970-01-01
  • 2021-03-01
  • 1970-01-01
  • 2021-06-25
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多