[英]Asp.Net Core WebAPI CORS Not working
I am trying to implement the WebAPI Service by using .Net Core and I couldn't manage to set up the CORS working correctly. 我正在尝试使用.Net Core实现WebAPI服务,我无法设置CORS正常工作。
I got the main application 'MainApp' and it's going to generate the Invoice on the fly and I want to promote it as the service. 我得到了主应用程序'MainApp',它将动态生成Invoice,我想将其作为服务进行推广。 This is not a pure WebAPI application.
这不是纯粹的WebAPI应用程序。 I just want to add this InvoiceController as the WebAPI and there are other Controllers such as HomeController, ProductsController, etc... with views and cshtml.
我只想添加这个InvoiceController作为WebAPI,还有其他控制器,如HomeController,ProductsController等...带有视图和cshtml。
I got separate Classic WebForm .Net Application which is going to call that InvoiceGeneration Service via Ajax and display values on the website. 我得到了单独的Classic WebForm .Net Application,它将通过Ajax调用InvoiceGeneration Service并在网站上显示值。
When I run my ajax script, I got this famous CORS error. 当我运行我的ajax脚本时,我得到了这个着名的CORS错误。
This is my ajax Get method. 这是我的ajax Get方法。 It doesn't matter whether I put
xhrFields
or not. 我是否放
xhrFields
并不重要。 I even changed dataType: 'jsonp'
and it still gives me the same error. 我甚至改变了
dataType: 'jsonp'
,它仍然给我同样的错误。
$.ajax({
type: "GET",
url: 'http://localhost:57012/invoice/test/123',
dataType: 'json',
contentType: 'application/json',
success: function (data) {
console.log(data);
},
xhrFields: {
withCredentials: true
}
});
InvoiceController.cs InvoiceController.cs
My Invoice Service is very simple... Just one method which is returning some JSON values. 我的发票服务非常简单......只有一种方法可以返回一些JSON值。
Since I am using Policy and Claims to determine the security, I put AllowAnonymous
attribute. 由于我使用Policy和Claims来确定安全性,因此我将
AllowAnonymous
属性。 Even though I remove that restriction, it still doesn't work. 即使我删除了这个限制,它仍然无法正常工作。
public class InvoiceController : Controller
{
[HttpGet]
[AllowAnonymous]
[EnableCors("AllowAll")]
public async Task<IActionResult> Test(string id)
{
return new JsonResult(id);
}
}
Startup.cs Startup.cs
I added AllowAll Policy to allow all type of requests. 我添加了AllowAll Policy以允许所有类型的请求。
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<DbContexts.PJDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("PJConnection")));
services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
services.AddMvc()
.AddJsonOptions(o => o.SerializerSettings.NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)
.AddJsonOptions(o => o.SerializerSettings.ContractResolver = new Newtonsoft.Json.Serialization.DefaultContractResolver());
services.AddCors(options => options.AddPolicy("AllowAll", p => p.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader()
.AllowCredentials()));
services.AddAuthorization(options =>
{
options.AddPolicy(Constants.CONST_POLICY_SUPERADMIN, policy => policy.RequireRole(Constants.CONST_ROLE_SUPERADMIN));
options.AddPolicy(Constants.CONST_POLICY_STUDENT, policy => policy.RequireRole(Constants.CONST_ROLE_STUDENT, Constants.CONST_ROLE_ADMIN, Constants.CONST_ROLE_SUPERADMIN));
});
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, IOptions<AppSettings> AppSettings)
{
loggerFactory.AddConsole(Configuration.GetSection("Logging"));
loggerFactory.AddDebug();
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
}
app.UseStaticFiles();
if (env.IsProduction())
{
app.UseStaticFiles(new StaticFileOptions()
{
FileProvider = new PhysicalFileProvider(AppSettings.Value.FilePathToUpload),
RequestPath = new PathString("/Files"),
});
}
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
AuthenticationScheme = "Cookie",
LoginPath = new PathString("/Account/Login/"),
AccessDeniedPath = new PathString("/Account/Forbidden/"),
AutomaticAuthenticate = true,
AutomaticChallenge = true
});
app.UseCors("AllowAll");
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
}
Here is the interesting part. 这是有趣的部分。
I created another new .Net Core WebAPI project and copy this CORS Setup to the Startup.cs and InvoiceController to the new project. 我创建了另一个新的.Net Core WebAPI项目,并将此CORS安装程序复制到Startup.cs和InvoiceController到新项目。 CORS is working fine and my AJAX can call that method from the new project.
CORS工作正常,我的AJAX可以从新项目中调用该方法。
But I don't want to make multiple projects and can't I embed that WebAPI in the existing MVC WebApp Project? 但我不想创建多个项目,我不能将WebAPI嵌入现有的MVC WebApp项目中吗?
I have seen some tutorials which is running both WebAPIs and MVC Controllers side by side in the same project (obviously they are in the same domain. So, CORS is not a problem for them). 我已经看到一些教程在同一个项目中同时运行WebAPI和MVC控制器(显然它们位于同一个域中。因此,CORS对他们来说不是问题)。 Very confusing.
非常混淆。
Could you guys please help me with it? 你能帮帮我吗?
PS. PS。 This Html5Rocks tutorial js script doesn't work too.
这个Html5Rocks教程js脚本也不起作用。
In my opinion, I don't think there is nothing wrong with JqueryAJAX script. 在我看来,我认为JqueryAJAX脚本没有任何问题。 I got another pure WebAPI .Net Core service and I managed to set up the CORS correctly with the same 'AllowAll Policy' code.
我有另一个纯WebAPI .Net Core服务,我设法使用相同的'AllowAll Policy'代码正确设置CORS。 I can call that service from any cross domain websites by using this simple Jquery script.
我可以使用这个简单的Jquery脚本从任何跨域网站调用该服务。
$.ajax({
type: "GET",
url: 'http://oakapi/staff/byid/2618',
dataType: 'json',
contentType: 'application/json',
success: function (data) {
console.log(data);
}
});
我认为service.AddCors()应该放在service.AddMvc()之前。
set ajax like this: 像这样设置ajax:
$.ajax({
type: "GET",
url: 'http://oakapi/staff/byid/2618',
dataType: 'jsonp',
contentType: 'application/javascript',
success: function (data) {
console.log(data);
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.