【发布时间】:2021-02-08 00:04:48
【问题描述】:
它会在 Ajax 调用中引发此错误。 我还在 Startup.cs 中使用命名策略尝试了这些行。我在网上找到的所有方法都不起作用。 我确定我在某个地方犯了一些愚蠢的错误,我没有看到它。
builder.WithOrigins("https://localhost:44380")
builder.WithOrigins("localhost:44380")
builder.WithOrigins("localhost")
[EnableCors("MyPolicy")] //in Controller.cs
Controller.cs
[Route("api/itexit")]
[EnableCors]
[ApiController]
public class ITExitController : ControllerBase
{
//code...
}
Startup.cs
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers();
services.AddSwaggerGen();
services.AddCors();
string connectionString = Configuration.GetConnectionString("DefaultConnection");
services.AddDbContext<CoCFormsContext>(options => options.UseSqlServer(connectionString));
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseSwagger();
app.UseSwaggerUI(c =>
{
c.SwaggerEndpoint("/swagger/v1/swagger.json", "CoCForms.API");
});
app.UseHttpsRedirection();
app.UseRouting();
app.UseCors(builder =>
{
builder
.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader();
});
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
来自 .cshtml 页面的 Ajax 调用
$.ajax({
url: url,
type: "GET",
crossDomain: true,
dataType: 'json',
//dataType: 'jsonp',
success: function (data,textstatus,jqXHR) {
//process data
},
error: function (jqXHR, textstatus, exception) {
//process exception
}
});
【问题讨论】:
标签: c# ajax .net-core cors asp.net-core-webapi