【发布时间】: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