简体   繁体   English

将标头添加到无法在asp.net中工作的iis静态文件中

[英]Adding headers to iis static files not working in asp.net CORE

I want to add extra headers like Access-Control-Allow-Origin to my webAPI in order to consume this data in another project. 我想向我的webAPI添加诸如Access-Control-Allow-Origin类的额外标题,以便在另一个项目中使用此数据。 At the moment I'm having this error: 目前,我遇到此错误:

Failed to load http://localhost:49932/api/Restaurantes : No 'Access-Control-Allow-Origin' header is present on the requested resource. 无法加载http:// localhost:49932 / api / Restaurantes :所请求的资源上没有'Access-Control-Allow-Origin'标头。 Origin ' http://localhost:4200 ' is therefore not allowed access. 因此,不允许访问源' http:// localhost:4200 '。

The 49932 port runs my API and 4200 port is my AngularJS client. 49932端口运行我的API,而4200端口是我的AngularJS客户端。 I have already tried adding them as suggested in this answer but didn't worked: 我已经尝试按照此答案中的建议添加它们,但没有成功:

in appsettings.json: 在appsettings.json中:

{
"ConnectionStrings": {
"ConexaoRestaurante": "data source=DESKTOP-R1CQGV1\\SQLEXPRESS;integrated security=SSPI;"
},
  "Logging": {
  "IncludeScopes": false,
"Debug": {
  "LogLevel": {
    "Default": "Warning"
  }
},
"Console": {
  "LogLevel": {
    "Default": "Warning"
  }
},
"StaticFiles": {
  "Headers": {
    "Access-Control-Allow-Origin": "*",
    "Access-Control-Allow-Headers": "Content-Type",
    "Access-Control-Allow-Methods": "GET, HEAD, POST, PUT, DELETE, CONNECT, OPTIONS, TRACE, PATCH"
     }
   }
 }
}

In the Configure method: Configure方法中:

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
        // tried both the commented and uncommented part:
        app.UseStaticFiles(new StaticFileOptions()
        {
            OnPrepareResponse = (context) =>
            {
                // Disable caching for all static files.
                context.Context.Response.Headers["Access-Control-Allow-Origin"] = Configuration["StaticFiles:Headers:Access-Control-Allow-Origin"];
                context.Context.Response.Headers["Access-Control-Allow-Headers"] = Configuration["StaticFiles:Headers:Access-Control-Allow-Headers"];
                context.Context.Response.Headers["Access-Control-Allow-Methods"] = Configuration["StaticFiles:Headers:Access-Control-Allow-Methods"];
            }
        }); 

        /*
        app.UseStaticFiles(new StaticFileOptions()
        {
            OnPrepareResponse = (context) =>
            {
                context.Context.Response.Headers["Access-Control-Allow-Origin"] = "*";
                context.Context.Response.Headers["Access-Control-Allow-Headers"] = "Content-Type";
                context.Context.Response.Headers["Access-Control-Allow-Methods"] = "GET, HEAD, POST, PUT, DELETE, CONNECT, OPTIONS, TRACE, PATCH";
            }
        });
        */

        app.UseMvc();

}

I also tried creating the Web.config which is not created when you start a framework Core project and adding the config as following: 我还尝试创建Web.config,但在启动框架Core项目并按如下所示添加配置时未创建该Web.config:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
 <system.webServer>
  <httpProtocol>
    <customHeaders>
        <add name="Access-Control-Allow-Origin" value="*" />
        <add name="Access-Control-Allow-Headers" value="Content-Type" />
        <add name="Access-Control-Allow-Methods" value="GET, HEAD, POST, PUT, DELETE, CONNECT, OPTIONS, TRACE, PATCH" />
    </customHeaders>
  </httpProtocol>
 </system.webServer>
</configuration>

So I guess I'm doing something wrong outside of this part, anyone knows what can be wrong here? 所以我想我在这部分之外做错了什么,有人知道这有什么错吗?

Cors is more than just the headers, refer to this for more info in .NET. CORS不仅仅是标题更多,请参阅在.NET更多信息。

In order to set CORS in .NET Core you need to add the Cors Services and configure them. 为了在.NET Core中设置CORS,您需要添加Cors Services并对其进行配置。

In the ConfigureServices add the following call: ConfigureServices添加以下调用:

public void ConfigureServices(IServiceCollection services)
{
    services.AddCors();
}

And in your Configure method: 并在您的Configure方法中:

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
    // Shows UseCors with CorsPolicyBuilder.
    app.UseCors(builder =>
       builder.WithOrigins("http://localhost:4200").AllowAnyHeader());
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM