【问题标题】:CORS Net Core 3.1CORS 网络核心 3.1
【发布时间】:2020-10-16 16:46:08
【问题描述】:

我的代码有这个问题;我尝试从我的本地主机调用 api 以在网络中寻址,我在 Web 控制台中出现此错误:

我认为我的本地主机中的 CORS 没问题,但这不起作用:“...CORS 标头 'Access-Control-Allow-Origin' 缺失”

我在visual studio 2019编译,我的api在网上;但我从 localhost 探查这段代码。

这是我的代码启动:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Mail;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.EntityFrameworkCore;
using IDCA.Models;

namespace IDCA
{
 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)
    {
        // Add CORS policy
        services.AddCors(
          options => options.AddPolicy("foo",
          builder => builder.AllowAnyOrigin()
          .AllowAnyHeader()
          .AllowAnyMethod()
          )
       );


        services.AddDbContext<TodoContext>(options =>
               options.UseSqlServer(Configuration.GetConnectionString("RazorPagesMovieContext")));
        services.AddControllers();

        services.AddScoped<SmtpClient>((serviceProvider) =>
        {
            var config = serviceProvider.GetRequiredService<IConfiguration>();
            return new SmtpClient()
            {
                Host = config.GetValue<String>("Email:Smtp:Host"),
                Port = config.GetValue<int>("Email:Smtp:Port"),
                Credentials = new NetworkCredential(
                        config.GetValue<String>("Email:Smtp:Username"),
                        config.GetValue<String>("Email:Smtp:Password")
                    )
            };
        });
        services.AddMvc();

        services.AddRazorPages();
    }

    // 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("/Error");
            // 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.UseDefaultFiles();
        app.UseStaticFiles();

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

        app.UseAuthorization();

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

}

【问题讨论】:

  • 尝试将全局异常处理程序添加到您的项目中,看看它是否有效。我认为您在项目中的某些地方遇到了异常,并且未处理的异常将清除 cors 标头

标签: asp.net-core cors


【解决方案1】:

核心 2.2 的配置:

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

核心 3.0 的配置:

services.AddCors(options => {
      options.AddPolicy("foo", builder =>
      {

           builder                    
                .WithOrigins("http://*.*.*.*")
                .AllowAnyMethod()
                .AllowAnyHeader()
                .AllowCredentials();
      });
    });
 

试试

 app.UseEndpoints(endpoints =>
            {
                endpoints.MapRazorPages();

                endpoints.MapControllers().RequireCors("foo");
            });

详情见此链接:https://docs.microsoft.com/en-us/aspnet/core/security/cors?view=aspnetcore-3.1

【讨论】:

  • 我尝试了你发布的链接,但是 3 个选项中的任何一个都可以,我真的不知道是什么错误。 ://
猜你喜欢
  • 1970-01-01
  • 2021-02-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-08-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多