c# - 仅在 API 的一项操作中出现 CORS 策略错误
问题描述
我制作了一个 .net core (2.2) API,一开始我遇到了 Access-Control-Allow-Origin 错误,但是当我在 Startup.cs 中添加 CORS 策略时,它得到了修复。问题是我添加了另一个 POST 方法,它抛出了同样的错误。我已经尝试了很多我在互联网上看到的建议,但没有一个有效。
顺便说一句,我可以访问服务器。
我在ConfigureServices
函数中添加了这一行:
services.AddCors(options =>
{
options.AddDefaultPolicy(builder =>
{
builder.AllowAnyOrigin();
builder.AllowAnyMethod();
builder.AllowAnyHeader();
builder.AllowCredentials();
});
});
在Configure
函数中我添加了这个:
app.UseCors();
这是引发错误的 post 方法:
[HttpPost]
public async Task<ActionResult<IActionResult>> PostRackSections(int rows, int cols)
{
var lastRackSlot = _context.RackSlots.OrderBy(rs => rs.Row).ThenBy(rs => rs.Column).Last();
for (byte i = (byte)(lastRackSlot.Row.ElementAt(0) + 1); i <= lastRackSlot.Row.ElementAt(0) + rows; i++)
{
for (int j = 1; j <= lastRackSlot.Column; j++)
{
_context.RackSlots.Add(new RackSlots { Row = Encoding.ASCII.GetString(new byte[] { i }), Column = j, Enabled = true });
}
}
for (int j = lastRackSlot.Column + 1; j <= lastRackSlot.Column + cols; j++)
{
for (byte i = (byte)'A'; i <= lastRackSlot.Row.ElementAt(0); i++)
{
_context.RackSlots.Add(new RackSlots { Row = Encoding.ASCII.GetString(new byte[] { i }), Column = j, Enabled = true });
}
}
try
{
await _context.SaveChangesAsync();
}
catch (DbUpdateException ex)
{
throw;
}
return NoContent();
}
这就是我调用 API 的方式:
const fnAddNewSlots = () => {
let rows = $("#ntbRows").val();
let cols = $("#ntbCols").val();
$.post("url", (data) => {
toastr.success("New slots added successfully");
}).fail((e) => {
toastr.error("Error trying to add new slots");
console.log(e);
});
}
这是错误:
Access to XMLHttpRequest at 'url' from origin 'http://localhost' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
编辑:
这是我的启动:
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)
{
services.AddRouting();
services.AddCors(o => o.AddPolicy("AllowAllOrigins",
builder =>
{
builder.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader();
}));
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
services.AddDbContext<context>();
// Register the Swagger generator, defining 1 or more Swagger documents
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new OpenApiInfo
{
Version = "v1",
Title = "API",
Description = "API",
});
// Set the comments path for the Swagger JSON and UI.
var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);
c.IncludeXmlComments(xmlPath);
});
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
app.UseCors("AllowAllOrigins");
// 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("v1/swagger.json", "API");
});
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
// 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.UseMvc();
}
}
解决方案
尝试使用以下语法代替默认的 cors 策略来启动您的启动:
services.AddCors(o => o.AddPolicy("AllowAllOrigins",
builder =>
{
builder.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader();
}));
并且您的 UseCors 方法应该介于 app.UseHttpsRedirection()、app.UseRouting 和 app.UseAuthourization 之间
app.UseHttpsRedirection(); // if needed
app.UseStaticFiles(); //if needed
app.UseRouting()
....
.....
app.UseCors("AllowAllOrigins");
....
....
app.UseAuthorization(); // if you need the one
推荐阅读
- c - do-while 循环进入 for 循环
- php - 我可以在 PowerShell 中的另一个变量中按名称设置变量值吗
- ios - 重新启用 Firebase 快照侦听器 (ListenerRegistration) Swift
- laravel - 如何忽略要上传到 Git 的文件夹?
- pagespeed - 此 PageSpeed Insight 报告中的“来源摘要”是什么意思?
- python - 如何决定是在脚本中实现scrapy还是将其用作框架
- java - 我该如何解决这个问题?我认为这与return语句有关
- javascript - 找不到带有 **/*.test.js 的模块
- spark-streaming - 带有 Azure 事件中心的 Azure AAD pod 标识
- git - 如何从提交树的基础创建一个新的 git 分支,它与 master 分支没有共同提交?对于 gh 页面