在Aps核心项目中启用CORS的问题

本文关键字:CORS 问题 启用 Aps 核心 项目 | 更新日期: 2023-09-27 18:04:06

大家!

我很难在Asp中配置CORS。核心项目。

这是我的Startup.cs文件:

using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.DependencyInjection;
using System.IdentityModel.Tokens.Jwt;
using Microsoft.AspNetCore.Mvc.Cors.Internal;
namespace Api
{
    public class Startup
    {
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvcCore()
                .AddJsonFormatters()
                .AddAuthorization();
            services.AddCors(options =>
            {
                options.AddPolicy("AllowSpecificOrigin",
                    builder => builder.WithOrigins("http://localhost:54540").AllowAnyHeader().AllowAnyMethod().AllowCredentials());
            }
            );
            services.Configure<MvcOptions>(options =>
            {
                options.Filters.Add(new CorsAuthorizationFilterFactory("AllowSpecificOrigin"));
            });
        }
        public void Configure(IApplicationBuilder app)
        {
            JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear();
            app.UseIdentityServerAuthentication(new IdentityServerAuthenticationOptions
            {
                Authority = "http://localhost:54540",
                RequireHttpsMetadata = false,
                ScopeName = "api1",
                AutomaticAuthenticate = true
            });
            app.UseMvc();
            app.UseCors("AllowSpecificOrigin");
        }
    }
}

这是我的请求:

$.ajax({
                type: "GET",
                url: "http://localhost:1773/Claims/",
                headers: {
                    Authorization: "Bearer " + getUrlParameter("access_token"),
                },
                xhrFields: {
                    withCredentials: true
                }
            }).done(function (data) {
                alert(data);
            });

我收到的回复是:

XMLHttpRequest cannot load http://localhost:1773/Claims/. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:54540' is therefore not allowed access. The response had HTTP status code 500.

我在控制器中添加了[EnableCors("AllowSpecificOrigin"(]。

如果有人能帮助我,我将非常感激。

在Aps核心项目中启用CORS的问题

如果在CORS中间件之前添加MVC/IdentityServer中间件,则它将不起作用,因为Identity服务器中间件(假设由其处理/声明(将处理请求,并且不会调用后面的MVC和CORS中间件。