我试图弄清楚如何防止在开发人员工具中显示cors错误。我收到cors错误的方式是,当我使用某个应用程序时,但是在另一个选项卡/窗口中,我注销了该应用程序,但随后又回到另一个选项卡并尝试进行工作。下面是我的ajax电话。
function RemoveScholarshipRequest(id, name) {
if (confirm("Are you sure you want to delete the scholarship request for " + name + "?")) {
var dataSource = $('#Pending').data('kendoGrid').dataSource;
$.ajax({
type: "POST",
url: '@Url.Action("RemoveRequest", "Admin")',
data: {id: id}
}).done(function (response, data, xhr) {
if (response.success) {
dataSource.read();
alert(response.responseText);
}
else if (!response.success) {
if (response.responseText === "Not Authenticated")
alert(response.responseText);
console.log("error", data.status);
//This shows status message eg. Forbidden
console.log("STATUS: "+JSON.stringify(xhr.status));
}
}).fail(function (response) {
console.log(response);
console.log(JSON.stringify(response));
//window.location.href = "/forms/ScholarshipDisbursement/Admin/PendingRequests";
});
}
}
上面的ajax方法调用的控制器动作如下:
[AllowAnonymous]
[HttpPost]
public ActionResult RemoveRequest(string id)
{
if (!User.Identity.IsAuthenticated)
{
return Json(new { success = false, responseText = "Not Authenticated" }, JsonRequestBehavior.AllowGet);
}
if (User.IsInRole("Developer") || User.IsInRole("BannerAdmin"))
{
new ScholarshipRequestStore().DeleteScholarshipRequest(id);
return Json(new { success = true, responseText = "Successfully deleted" }, JsonRequestBehavior.AllowGet);
}
else
{
return Json(new { success = false, responseText = "You are not an authorized user" }, JsonRequestBehavior.AllowGet);
}
}
我解决cors错误的一种方法是将AllowAnonymous放在方法上,然后在方法本身中检查身份验证,但我真的不喜欢这个想法。是否有另一种方法可以解决此问题?
答案 0 :(得分:1)
允许匿名不会解决此问题,相反,您需要在api中发送allow origin标头。您可以通过在启动类中启用COR来做到这一点,如下所示:
public void ConfigureServices(IServiceCollection services)
{
// Add Cors
services.AddCors(o => o.AddPolicy("MyPolicy", builder =>
{
builder.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader();
}));
// Add framework services.
services.AddMvc();
services.Configure<MvcOptions>(options =>
{
options.Filters.Add(new CorsAuthorizationFilterFactory("MyPolicy"));
});
...
...
...
}
// This method gets called by the runtime. Use this method to configure
//the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env,
ILoggerFactory loggerFactory)
{
loggerFactory.AddConsole(Configuration.GetSection("Logging"));
loggerFactory.AddDebug();
// Enable Cors
app.UseCors("MyPolicy");
//app.UseMvcWithDefaultRoute();
app.UseMvc();
...
...
...
}
,然后在控制器上使用“启用cors”属性
[EnableCors("MyPolicy")]
[AllowAnonymous]
[HttpPost]
public ActionResult RemoveRequest(string id)
阅读本文以获得更好的主意https://docs.microsoft.com/en-us/aspnet/core/security/cors?view=aspnetcore-2.2
注意:我已经允许任何来源与API进行通讯,您可以指定所需的任何来源,例如“ https://example.com”
答案 1 :(得分:0)
AllowAnonymous无法解决“跨域”请求。您遇到的问题是由于浏览器中的选项卡式浏览具有经过身份验证的会话的共享存储。当您注销选项卡1时,会话cookie被删除,然后选项卡2不再经过身份验证。这就是为什么AllowAnonymous之所以可以“工作”的原因,因为没有当前经过身份验证的会话,您就是匿名用户。
另一方面,CORS是当您允许对http://myservice.com的呼叫来自诸如http://myclient.com之类的其他主机时。匿名访问对此不会有任何影响。