【发布时间】:2019-12-07 10:57:35
【问题描述】:
我在 web.api 的生产服务器上部署了应用程序,但在浏览器控制台中出现以下错误(似乎已解决):
访问 XMLHttpRequest
'https://ebbtelemetrywebapi.azurewebsites.net/api//events' 来自原点 'https://ebbwatelem.azurewebsites.net' 已被 CORS 阻止 政策:没有“Access-Control-Allow-Origin”标头出现在 请求的资源。
在此错误之前,我有以下问题(似乎已解决):
被调用函数的头部如下:
public async Task<IEnumerable<CosmosDBEvents>> GetAsync([FromBody]EventsGetTwoParamsDto dto)
DTO 声明如下:
public class EventsGetTwoParamsDto
{
public string DeviceIdorId { get; set; }
public string Action2 { get; set; }
}
ajax 调用如下:
$.ajax({
type:"POST",
url: ENV.apiUrl+'/events',
data: JSON.stringify({DeviceIdorId: ENV.deviceId, Action2 : "Pagina5"}),
dataType: "json",
contentType: 'application/json;charset=UTF-8',
success: function(data){
console.log("RISPOSTA", data);
}
});
Startup.cs/ConfigurationServices 方法包含以下行:
services.AddCors(); // Make sure you call this previous to AddMvc
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
并且通过 Startup.cs/Configure 方法包含:
app.UseCors(
options=> options.AllowAnyOrigin()
.AllowAnyHeader()
.AllowAnyMethod()
.AllowCredentials());
我做错了什么?
提前致谢。 西蒙娜
所有问题都与第二个问题有关,解决了更改控制器中方法的声明,如下所示:
[HttpPost]
public async
Task<IEnumerable<CosmosDBTelemetry>>GetAsync(TelemetriesTwoParamsDto dto)
谢谢大家, 西蒙娜
【问题讨论】:
-
在 Startup.cs 类 ConfigureServices() 中添加以下代码
services.AddCors(options => { options.AddPolicy("AllowAllOrigins", builder1 => { builder1 .AllowAnyOrigin() .AllowAnyHeader() .AllowAnyMethod() .AllowCredentials(); }); });在同一个类的 Configure 方法中,您必须添加app.UseCors("AllowAllOrigins") -
我可以看到您的 Web 应用程序托管在 azure 上。在 azure 中有一个启用 cors 的设置。 Azure CORS Configuration
-
查看 Azure 存储 cors 配置:docs.microsoft.com/en-us/rest/api/storageservices/…