Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/asp.net-core/3.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 core 在asp net core web api v3.0中启用CORS时出现问题_Asp.net Core_Cors_Asp.net Core 3.0_.net Core 3.0 - Fatal编程技术网

Asp.net core 在asp net core web api v3.0中启用CORS时出现问题

Asp.net core 在asp net core web api v3.0中启用CORS时出现问题,asp.net-core,cors,asp.net-core-3.0,.net-core-3.0,Asp.net Core,Cors,Asp.net Core 3.0,.net Core 3.0,我在我的web API项目中使用asp net core 3.0。我创建了各种API,所有API都可以通过Swagger或Postman访问。但当试图通过任何其他客户端(如React)访问相同内容时,将接收到方法not allowed(405错误代码)。在进一步投资时,我发现,首先,从React应用程序接收到选项请求,net core web API应用程序给出405状态代码。此外,我发现我需要启用所有方法以及来自net core应用程序的源来接受所有类型的请求,否则它将不接受OPTION请求。

我在我的web API项目中使用asp net core 3.0。我创建了各种API,所有API都可以通过Swagger或Postman访问。但当试图通过任何其他客户端(如React)访问相同内容时,将接收到方法not allowed(405错误代码)。在进一步投资时,我发现,首先,从React应用程序接收到选项请求,net core web API应用程序给出405状态代码。此外,我发现我需要启用所有方法以及来自net core应用程序的源来接受所有类型的请求,否则它将不接受OPTION请求。为了实现这一点,我在startup.cs文件中启用了CORS策略,但仍然运气不佳。以下是我的startup.cs文件:

public class Startup
{
    public Startup(IConfiguration configuration)
    {

        Configuration = configuration;

        var elasticUri = Configuration["ElasticConfiguration:Uri"];

        Log.Logger = new LoggerConfiguration()
            .Enrich.FromLogContext()
            .Enrich.WithExceptionDetails()
            .WriteTo.Elasticsearch(new ElasticsearchSinkOptions(new Uri(elasticUri))
            {
                MinimumLogEventLevel = LogEventLevel.Verbose,
                AutoRegisterTemplate = true,
            })
        .CreateLogger();


    }

    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.Configure<IISServerOptions>(options =>
        {
            options.AutomaticAuthentication = false;
        });
        services.Configure<ApiBehaviorOptions>(options =>
        {
            //To handle ModelState Errors manually as ApiController attribute handles those automatically
            //and return its own response.
            options.SuppressModelStateInvalidFilter = true;
        });

       services.AddCors(options =>
        {
            options.AddPolicy("CorsPolicy",
                builder => builder.AllowAnyOrigin()
                .AllowAnyMethod()
                .AllowAnyHeader());
        });

        services.AddControllers(options =>
        {
            //To accept browser headers.
            options.RespectBrowserAcceptHeader = true;
        }).
         AddNewtonsoftJson(options =>
         {
             // Use the default property (Pascal) casing
             options.SerializerSettings.ContractResolver = new DefaultContractResolver();
             options.SerializerSettings.NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore;

         }).
        AddJsonOptions(options =>
         {
             //Not applying any property naming policy
             options.JsonSerializerOptions.PropertyNamingPolicy = null;
             options.JsonSerializerOptions.IgnoreNullValues = true;

         }).
        AddXmlSerializerFormatters().
        AddXmlDataContractSerializerFormatters();
    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IWebHostEnvironment env, ILoggerFactory loggerFactory)
    {
        app.UseCors("CorsPolicy");

        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }      

        // Enable middleware to serve generated Swagger as a JSON endpoint.
        app.UseSwagger();

        // Enable middleware to serve swagger-ui (HTML, JS, CSS, etc.),
        // specifying the Swagger JSON endpoint.
        app.UseSwaggerUI(c =>
        {
            c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1");
        });

        app.UseRouting();

        app.UseAuthentication();

        app.UseAuthorization();

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

        //Configuring serilog
        loggerFactory.AddSerilog();

    }
}
公共类启动
{
公共启动(IConfiguration配置)
{
配置=配置;
var elasticUri=Configuration[“ElasticConfiguration:Uri”];
Logger.Logger=新的LoggerConfiguration()
.Enrich.FromLogContext()的
.Enrich.WithExceptionDetails()
.WriteTo.Elasticsearch(新的ElasticsearchSinkOptions(新Uri(elasticUri))
{
MinimumLogEventLevel=LogEventLevel.Verbose,
AutoRegisterTemplate=true,
})
.CreateLogger();
}
公共IConfiguration配置{get;}
//此方法由运行时调用。请使用此方法将服务添加到容器中。
public void配置服务(IServiceCollection服务)
{
配置(选项=>
{
options.AutomaticAuthentication=false;
});
配置(选项=>
{
//当ApiController属性自动处理模型状态错误时,手动处理模型状态错误
//并返回它自己的响应。
options.SuppressModelStateInvalidFilter=true;
});
services.AddCors(选项=>
{
options.AddPolicy(“CorsPolicy”,
builder=>builder.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader());
});
services.AddControllers(选项=>
{
//接受浏览器标题。
options.reserverBrowserAcceptHeader=true;
}).
AddNewtonsoftJson(选项=>
{
//使用默认属性(Pascal)大小写
options.SerializerSettings.ContractResolver=新的DefaultContractResolver();
options.SerializerSettings.NullValueHandling=Newtonsoft.Json.NullValueHandling.Ignore;
}).
AddJsonOptions(选项=>
{
//不应用任何属性命名策略
options.JsonSerializerOptions.PropertyNamingPolicy=null;
options.JsonSerializerOptions.IgnoreNullValues=true;
}).
AddXmlSerializerFormatters()。
AddXmlDataContractSerializerFormatters();
}
//此方法由运行时调用。请使用此方法配置HTTP请求管道。
public void配置(IApplicationBuilder应用程序、IWebHostEnvironment环境、iLogger工厂)
{
附录UseCors(“公司政策”);
if(env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}      
//使中间件能够将生成的Swagger作为JSON端点提供服务。
app.UseSwagger();
//使中间件能够服务于swagger ui(HTML、JS、CSS等),
//指定Swagger JSON端点。
app.UseSwaggerUI(c=>
{
c、 SwaggerEndpoint(“/swagger/v1/swagger.json”,“我的API v1”);
});
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(端点=>
{
endpoints.MapControllers();
});
//配置serilog
loggerFactory.AddSerilog();
}
}
我试着用POSTMAN的OPTIONS方法测试相同的API。它还将Http状态代码设置为405。但是当尝试使用POST方法访问相同的请求时,我成功地收到了响应


上面的代码是否有问题,或者在Configure()中调用中间件的顺序是否有问题。

尝试添加扩展方法并修改启动类:

扩展方法:

public static void AddApplicationError(this HttpResponse response, string 
    message)
{
    response.Headers.Add("Application-Error", message);
    response.Headers.Add("Access-Control-Expose-Headers", "Application-Error");
    response.Headers.Add("Access-Control-Allow-Origin", "*");
}
Startup.cs:

        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);
                    }
                });
            });
        }

希望这至少有助于显示准确的错误消息

您需要在web api项目下的Startup.cs文件中添加Cors

  • Startup.cs中添加此变量
  • 只读字符串MyAllowSpecificCorigins=“\u MyAllowSpecificCorigins”

  • 在文件Startup.cs中的方法ConfigureServices中,在services.AddControllers()之前添加services.AddCors
  • ***您只能通过*以允许全部而不是通过http://localhost:4000","http://www.yourdomain.com 在原始方法中

  • 在文件Startup.cs中的方法Configure中,在app.UseAuthentication()之前添加app.UseCors
  • 应用程序UseCors(MyAllowSpecificCorigins)


    我认为这是实现我想要的东西的一种变通方法,但不是实现我想要的东西的正确方法。
        [HttpGet]
        public ActionResult GetAllEmployees()
    
        [HttpGet]
        public ActionResult GetCustomers()
    
    services.AddCors(options =>
    {
        options.AddPolicy(MyAllowSpecificOrigins,
        builder =>
        {
           builder.WithOrigins("http://localhost:4000",
           "http://www.yourdomain.com")
           .AllowAnyHeader()
           .AllowAnyMethod();
        });
    });
    
    services.AddControllers();