C# 使用“授权”属性时出现Cors策略错误

C# 使用“授权”属性时出现Cors策略错误,c#,asp.net-core,angular8,asp.net-core-3.0,authorize-attribute,C#,Asp.net Core,Angular8,Asp.net Core 3.0,Authorize Attribute,每当我在用户控制器上使用Authorize属性时,我都会收到一个cors策略错误。我使用Angular 8作为前端框架,使用asp.net core 3.0.0作为后端。如果我从控制器中删除Authorize属性,工作正常。 . 下面是我的startup.cs文件 using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Threading.Tasks; us

每当我在用户控制器上使用Authorize属性时,我都会收到一个cors策略错误。我使用Angular 8作为前端框架,使用asp.net core 3.0.0作为后端。如果我从控制器中删除Authorize属性,工作正常。 . 下面是我的startup.cs文件

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Threading.Tasks;
using AutoMapper;
using DatingApp.API.Data;
using DatingApp.API.Helpers;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Diagnostics;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;

namespace DatingApp.API {
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_3_0);
            services.AddDbContext<DataContext>(x => x.UseSqlite(Configuration.GetConnectionString("DefaultConnection")));
            services.AddCors(options =>
            {
                options.AddPolicy("CorsPolicy",
                    builder => builder.AllowAnyOrigin()
                    .AllowAnyMethod()
                    .AllowAnyHeader());
            });
            services.AddAutoMapper(typeof(DatingRepository).Assembly);
            services.AddScoped<IAuthRepository, AuthRepository>();
            services.AddScoped<IDatingRepository, DatingRepository>();

        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler(builder =>
                {
                    builder.Run(async context =>
                    {
                        context.Response.StatusCode = (int)HttpStatusCode.InternalServerError;

                        var error = context.Features.Get<IExceptionHandlerFeature>();
                        if (error != null)
                        {
                            context.Response.AddApplicationError(error.Error.Message);
                            await context.Response.WriteAsync(error.Error.Message);
                        }
                    });
                });
                // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
                // app.UseHsts();
            }
            app.UseHttpsRedirection();

            app.UseRouting();

            app.UseAuthorization();
            app.UseCors("CorsPolicy");
            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers().RequireCors("CorsPolicy");
            });

        }
    }
}
使用系统;
使用System.Collections.Generic;
使用System.Linq;
Net系统;
使用System.Threading.Tasks;
使用自动制版机;
使用DatingApp.API.Data;
使用DatingApp.API.Helpers;
使用Microsoft.AspNetCore.Builder;
使用Microsoft.AspNetCore.Diagnostics;
使用Microsoft.AspNetCore.Hosting;
使用Microsoft.AspNetCore.Http;
使用Microsoft.AspNetCore.HttpsPolicy;
使用Microsoft.AspNetCore.Mvc;
使用Microsoft.EntityFrameworkCore;
使用Microsoft.Extensions.Configuration;
使用Microsoft.Extensions.DependencyInjection;
使用Microsoft.Extensions.Hosting;
使用Microsoft.Extensions.Logging;
使用Microsoft.Extensions.Options;
命名空间DatingApp.API{
公营创业
{
公共启动(IConfiguration配置)
{
配置=配置;
}
公共IConfiguration配置{get;}
//此方法由运行时调用。请使用此方法将服务添加到容器中。
public void配置服务(IServiceCollection服务)
{
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_3_0);
services.AddDbContext(x=>x.UseSqlite(Configuration.GetConnectionString(“DefaultConnection”));
services.AddCors(选项=>
{
options.AddPolicy(“CorsPolicy”,
builder=>builder.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader());
});
AddAutoMapper(typeof(DatingRepository).Assembly);
services.addScope();
services.addScope();
}
//此方法由运行时调用。请使用此方法配置HTTP请求管道。
public void配置(IApplicationBuilder应用程序、IWebHostEnvironment环境)
{
if(env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
其他的
{
app.UseExceptionHandler(生成器=>
{
运行(异步上下文=>
{
context.Response.StatusCode=(int)HttpStatusCode.InternalServerError;
var error=context.Features.Get();
if(错误!=null)
{
context.Response.AddApplicationError(error.error.Message);
wait context.Response.WriteAsync(error.error.Message);
}
});
});
//默认的HSTS值为30天。您可能希望在生产场景中更改此值,请参阅https://aka.ms/aspnetcore-hsts.
//app.UseHsts();
}
app.UseHttpsRedirection();
app.UseRouting();
app.UseAuthorization();
附录UseCors(“公司政策”);
app.UseEndpoints(端点=>
{
endpoints.MapControllers().RequireCors(“CorsPolicy”);
});
}
}
}
这是我的用户控制器

首先我需要添加
app.UseAuthentication()
用于在startup.cs文件中添加身份验证作为中间件,然后我还需要在我的服务中配置相同的身份验证。 下面是在startup.cs文件中的修改

首先为什么要使用授权过滤器。我找不到您在服务中的何处配置了授权,尽管您将其添加到middlewareCORS中并不是关于授权。即使在我将authorize属性设置为last之后,也请查看获取相同错误的情况。在上面的链接中,我没有看到任何授权配置。能否将app.UseCors(“CorsPolicy”)代码移动到app.UseAuthorization()上方?中间件的添加顺序很重要!