Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/angular/28.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Asp.net .NET3.1API&;带NGINX代理的角度9 CORS_Asp.net_Angular_Nginx_Controller - Fatal编程技术网

Asp.net .NET3.1API&;带NGINX代理的角度9 CORS

Asp.net .NET3.1API&;带NGINX代理的角度9 CORS,asp.net,angular,nginx,controller,Asp.net,Angular,Nginx,Controller,我一直被一个从Angular 9UI web应用程序交换数据的问题所困扰。我知道这个领域有很多主题,但我无法让它发挥作用,我将与您分享我的代码,看看我是否能达到目的。如果.Net API配置错误、NGINX或Angular应用程序,我似乎无法找到根本原因。这是我的第一个“真正的”解决方案,所以我仍然在学习如何处理所有组件 我有一个.NET3.1APIONE控制器,公开MySQL数据库数据。 Angular应用程序位于NGIX代理服务器部署之后 从邮递员应用程序或导航到控制器地址,获取、放置、发布

我一直被一个从Angular 9UI web应用程序交换数据的问题所困扰。我知道这个领域有很多主题,但我无法让它发挥作用,我将与您分享我的代码,看看我是否能达到目的。如果.Net API配置错误、NGINX或Angular应用程序,我似乎无法找到根本原因。这是我的第一个“真正的”解决方案,所以我仍然在学习如何处理所有组件

我有一个.NET3.1APIONE控制器,公开MySQL数据库数据。 Angular应用程序位于NGIX代理服务器部署之后

从邮递员应用程序或导航到控制器地址,获取、放置、发布和删除请求。此外,GET请求在Angular应用程序中工作。但是,PUT、POST请求不起作用

我尝试过修改.NET API启动配置,但没有成功,在他们的教程之后添加了来自Microsoft的CORS Nugget包。完成此操作后,GET也停止工作。 执行PUT/POST请求时Angular App出错:

CORS策略已阻止从源“”访问“”处的XMLHttpRequest:对飞行前请求的响应未通过访问控制检查:请求的资源上不存在“访问控制允许源”标头

我尝试的是:

public void ConfigureServices(IServiceCollection services)
    {
        // ...

        // Add CORS policy
        services.AddCors(options =>
        {
            options.AddPolicy("test",
            builder =>
            {
                // Not a permanent solution, but just trying to isolate the problem
                builder.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader();
            });
        });

        services.AddControllers();
    }
 public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }

        app.UseHttpsRedirection();

        // Use the CORS policy
        app.UseCors("test");

        app.UseRouting();

        app.UseAuthorization();

        app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllers();
        });
    }
我的.Net控制器-为了简化,我只对PUT感兴趣

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using BeckerSmartFan.Data;
using BeckerSmartFan.Models;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;

namespace BeckerSmartFan.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    [AllowAnonymous]
    public class AlertsConfigController : ControllerBase
    {
        private readonly ConnectionStrings con;
        private readonly Data.MySqlConnector mySqlConnector;

        public AlertsConfigController(ConnectionStrings c)
        {
            con = c;
            mySqlConnector = new Data.MySqlConnector();
        }

        // GET: api/AlertsConfig
        [HttpGet]
        public async Task<IActionResult> Get([FromQuery]  IEnumerable<AlertsConfig> alertsConfigs, [FromQuery] string type)
        {
            return await Task.Run(() =>
            {
                var listAlertConfigs = mySqlConnector.GetAllAlertsConfigs(con, type);
                return listAlertConfigs != null ? (IActionResult)Ok(listAlertConfigs) : NotFound();
            });
        }  

        // PUT: api/AlertsConfig/
        [HttpPut]
        public async Task<IActionResult> Put([FromBody] AlertsConfig alertConfig)
        {
            return await Task.Run(() =>
            {
                var result = mySqlConnector.UpdateAlertConfig(con, alertConfig);
                return result > 0 ? (IActionResult)Ok(alertConfig) : BadRequest();
            });
        }    

    }
}
Chrome中的网络选项卡:

我发现了问题,问题是我在两个不同的地方配置了CORS策略,这种“安全总比抱歉好”的心态并不总是正确的。NGINX CORS和.NET API CORS配置发生冲突

为每个方法或控制器添加CORS数据注释

[EnableCors(来源:,标题:,方法:*”)

并在Startup.cs上配置CORS Microsoft Nugget包

    public class Startup
{
    readonly string MyAllowSpecificOrigins = "_myAllowSpecificOrigins";

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddCors(options =>
        {
            options.AddPolicy(name: MyAllowSpecificOrigins,
                              builder =>
                              {
                                  builder.WithOrigins("http://example.com",
                                                      "http://www.contoso.com");
                              });
        });

        services.AddControllers();
    }

    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }

        app.UseHttpsRedirection();
        app.UseStaticFiles();
        app.UseRouting();

        app.UseCors(MyAllowSpecificOrigins);

        app.UseAuthorization();

        app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllers();
        });
    }
}

或者使用NGINX,只要你觉得更简单。

我已经在我的计算机上本地尝试了一切(Angular App+API),而没有通过NGINX。在WEB API中添加了CORS Nugget配置,一切正常。那么,我在NGINX中的问题是什么?
   server {
                listen 80 default_server;
                listen [::]:80 default_server;

        root /var/www/WebApp;

        # Add index.php to the list if you are using PHP
        index index.html index.htm index.nginx-debian.html;

        server_name _;

        add_header 'Access-Control-Allow-Origin' '*';
        add_header 'Access-Control-Allow-Credentials' 'true';
        add_header 'Access-Control-Allow-Headers' 'Content-Type,Accept';
        add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS, PUT, DELETE';

  location / {
                # First attempt to serve request as file, then
                # as directory, then fall back to displaying a 404.
                try_files $uri $uri/ =404;
                proxy_pass         http://localhost:5000/;
                proxy_http_version 1.1;
                proxy_set_header   Upgrade $http_upgrade;
                proxy_set_header   Connection keep-alive;
                proxy_set_header   Host $host;
                proxy_cache_bypass $http_upgrade;
                proxy_set_header   X-Forwarded-For $proxy_add_x_forwarded_for;
                proxy_set_header   X-Forwarded-Proto $scheme;

        }

          location /api/FanDataTags {
                proxy_pass         http://localhost:5000/api/FanDataTags;

         }

        location /api/AlertsConfig {
                proxy_pass http://localhost:5000/api/AlertsConfig;
        }
server {
        listen 8080;
        listen [::]:8080;

        server_name _;

        root /var/www/Angular;

        location / {
                #directory, then fall back to displaying a 404.
                try_files $uri $uri/ /index.html;
                index index.html index.htm;
                #proxy_pass         http://localhost:8080/;
                #proxy_http_version 1.1;
                #proxy_set_header   Upgrade $http_upgrade;
                #proxy_set_header   Connection keep-alive;
                #proxy_set_header   Host $host;
                #proxy_cache_bypass $http_upgrade;
                #proxy_set_header   X-Forwarded-For $proxy_add_x_forwarded_for;
                #proxy_set_header   X-Forwarded-Proto $scheme;

        }
}
    public class Startup
{
    readonly string MyAllowSpecificOrigins = "_myAllowSpecificOrigins";

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddCors(options =>
        {
            options.AddPolicy(name: MyAllowSpecificOrigins,
                              builder =>
                              {
                                  builder.WithOrigins("http://example.com",
                                                      "http://www.contoso.com");
                              });
        });

        services.AddControllers();
    }

    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }

        app.UseHttpsRedirection();
        app.UseStaticFiles();
        app.UseRouting();

        app.UseCors(MyAllowSpecificOrigins);

        app.UseAuthorization();

        app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllers();
        });
    }
}