【问题标题】:Angular API Call on C# Web API Cors ExceptionC# Web API Cors 异常上的 Angular API 调用
【发布时间】:2021-08-19 20:25:31
【问题描述】:

我正在尝试从我的 Angular 前端对我的 C# Web API 进行 API 调用。 我已经通过 HTTP 和 HTTPS 尝试过。

HTTP:我收到 CORS 异常 HTTPS:我收到一个 CONNECTION CLOSED 异常

我也通过 Postman 进行了尝试,它工作正常,所以后端不应该是问题。

我正在使用 Angular HTTP 客户端。

【问题讨论】:

    标签: c# angular asp.net-web-api connection-close


    【解决方案1】:

    在 ConfigureServices 的 Startup.cs 文件中必须存在以下代码

    public void ConfigureServices(IServiceCollection services) method.
    {
                    services.AddCors(options => options.AddPolicy("CorsPolicy",
                      builder => builder
                      .WithOrigins("http://localhost:4200", "YOUR_REQUEST_ORIGIN_URI")
                      .AllowAnyMethod()
                      .AllowAnyHeader()
                      .AllowCredentials()));
    }
    

    【讨论】:

      【解决方案2】:

      cors 是浏览器的安全性,没有 api 中的 cors 配置在 postman 上工作,postman 不是网络浏览器。

      尝试在您的 api 上添加 Cors 配置

      1. [AspNet Web API]

      安装包

      Install-Package Microsoft.AspNet.WebApi.Cors

      编辑 WebApiConfig 文件,在 App_Start/WebApiConfig.cs

      public static class WebApiConfig
      {
          public static void Register(HttpConfiguration config)
          {
              //change www.example.com for you domain, like localhost
              var cors = new EnableCorsAttribute("www.example.com", "*", "*");
              config.EnableCors(cors);
          }
      }
      
      1. [.Net Core]

      编辑Startup.cs并添加CORS中间件和服务

      public class Startup
      {
          public void ConfigureServices(IServiceCollection services)
          {
              services.AddCors(options =>
              {
                  options.AddDefaultPolicy(
                      builder =>
                      {
                          //change www.example.com for you domain, like localhost
                          builder.WithOrigins("http://example.com");
                      });
              });
      
              services.AddControllers();
          }
      
          public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
          {
              if (env.IsDevelopment())
              {
                  app.UseDeveloperExceptionPage();
              }
      
              app.UseHttpsRedirection();
              app.UseStaticFiles();
              app.UseRouting();
      
              app.UseCors();
      
              app.UseAuthorization();
      
              app.UseEndpoints(endpoints =>
              {
                  endpoints.MapControllers();
              });
          }
      }
      

      参考文献

      AspNet WebApi .Net Core

      【讨论】:

        猜你喜欢
        • 2015-04-16
        • 2018-10-24
        • 2021-09-02
        • 2018-11-07
        • 1970-01-01
        • 2018-10-19
        • 2022-06-28
        • 2017-07-05
        • 2017-06-03
        相关资源
        最近更新 更多