我遇到了同样的问题。
最后在网上搜索后,我得出结论 web.config 对于 ASP.NET Core(中间件方法)来说已经过时了。
实际上,您想要使用 WEB.CONFIG(用于 IIS)的操作应该使用 ASP.NET Core app.config 或自定义中间件(新理念)来完成。
在我的情况下,我必须在我的 web.config(仅适用于具有 SSL 的生产环境)中放入以下部分:
<httpProtocol>
<customHeaders>
<add name="Strict-Transport-Security" value="max-age=31536000; includeSubDomains; preload" />
</customHeaders>
</httpProtocol>
因为 WEB.CONFIG 对于 ASP.NET Core 来说已经过时了(当然你仍然可以使用它)。您必须使用 app.config 或中间件方法(两者都可以互补)。这是我用中间件代码替换 web.config 的示例。
在 Startup.cs(此文件是您的项目根目录)中,您必须注册您的自定义中间件 - 只需添加 1 行 (app.UseMyCustomMiddleware),如下所示:
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
...
if (env.IsDevelopment())
{
...
}
else
{
...
app.UseMyCustomMiddleware();
}
...
}
MyCustomMiddleware 类的实现应该是这样的(为了清楚起见,我将 2 个类放在同一个文件中):
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using System.Threading.Tasks;
namespace MyWeb // Change this name to match your project name if needed
{
public static class MyCustomMiddlewareExtensions
{
public static IApplicationBuilder UseMyCustomMiddleware(this IApplicationBuilder app)
{
return app.UseMiddleware<MyCustomMiddleware>();
}
}
public class MyCustomMiddleware
{
private readonly RequestDelegate _next;
public MyCustomMiddleware(RequestDelegate next)
{
this._next = next;
}
public async Task Invoke(HttpContext context)
{
// Put your code here (at my concern, i need the code below)
context.Response.Headers.Add("Strict-Transport-Security", "max-age=31536000; includeSubDomains; preload");
// Very important
await _next(context);
}
}
}
希望我的解释和示例对您有所帮助。