В запрошенном ресурсе отсутствует заголовок Access-Control-Allow-Origin. ASP.NET WebForms для веб-API 2
Я пытаюсь сделать ajax-вызов со страницы веб-форм на контроллер веб-API 2, но получаю следующую ошибку:
В запрошенном ресурсе отсутствует заголовок "Access-Control-Allow-Origin". Происхождение поэтому не допускается. Ответ имел HTTP-код состояния 401.
Я потратил некоторое время на поиск ответа, но ничего не получается.
WebForms:
Первая попытка -
$.ajax({
type: 'GET',
url: 'http://localhost:58513/api/DragDropUploader',
dataType: 'json',
success: function (data) {
helloWorldLabel.text("Success");
},
failure: function () {
alert("Failure");
helloWorldLabel.text("Failure");
}
});
Вторая попытка -
$.ajax({
type: 'GET',
url: serviceUrl
}).done(function (data) {
helloWorldLabel.text(data);
}).error(function (jqXHR, textStatus, errorThrown) {
helloWorldLabel.text(jqXHR.responseText || textStatus);
});
Третья попытка -
$.getJSON("http://localhost:58513/api/DragDropUploader",
function (data) {
alert("test");
helloWorldLabel.text(data);
});
Веб API 2:
WebApiConfig -
public static void Register(HttpConfiguration config)
{
// Web API configuration and services
// Web API routes
config.MapHttpAttributeRoutes();
EnableCorsAttribute cors = new EnableCorsAttribute("*", "*", "*");
config.EnableCors(cors);
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
Контроллер -
[EnableCors(origins: "*", headers: "*", methods: "*")]
public class DragDropUploaderController : ApiController
{
// GET api/DragDropUpload
[HttpGet]
public HttpResponseMessage Get()
{
return new HttpResponseMessage()
{
Content = new StringContent("Hello World")
};
}
}