[英]Possible null reference return warning in ConfigureServices()
[英]Null WebRootPath in ConfigureServices for Blazor Hosted
我想在 Blazor 托管解决方案中从Blazor.Server.Startup.ConfigureServices
中访问 web 根路径。
我已将IWebHostEnvironment
注入Startup
构造函数并将其保存为名为“WebHostEnvironment”的属性。 问题是在 ConfigureServices 中, WebHostEnvironment.WebRootPath
总是 null。
我已经验证过:
wwwroot
文件夹存在于我的 Blazor.Client 项目中。app.UseStaticFiles();
已在Startup.Configure
中调用(不确定是否有必要,但这是我发现的为数不多的推荐解决方案之一)。 这似乎是一个常见问题(也许 WebRootPath 仅在某些情况下才会填充 - 例如在我的应用程序发布/部署之后?),但是我无法在任何地方找到明确,明确的答案而且我不确定是什么我可以在ConfigureServices
中获取 web 根路径。
虽然与问题没有直接关系,但我正在尝试获取令牌端点的路径,以便我可以在新的OpenApiAuthFlow
中为 Swashbuckle 的AddSwaggerGen
服务配置TokenUrl
属性。 我不想指定本地主机 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
中做您想做的事。
如果您想访问wwwroot文件夹,请将代码放入Configure
方法或ServiceCollection
方法中,您可以获得IServiceProvider
实例,例如.AddTransient
。
样本
services.AddTransient(p =>
{
var environment = p.GetRequiredService<IWebHostEnvironment>();
var path = environment.WebRootPath;
return new Stuff(path);
});
尝试将“wwwroot”文件夹添加到您的 Blazor 服务器项目(假设您的解决方案中有标准的 3 个项目 - 客户端、服务器和共享)。 该文件夹本身可以为空,但它必须存在,否则 WebRootPath 将为 null。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.