【发布时间】:2015-11-18 09:10:35
【问题描述】:
问题背景:
我有一个带有单个视图的基本 MVC 应用程序,它使用 AJAX 请求来调用我在 Azure 中托管的一个简单的 WepApi 应用程序。 WebApi 用于呈现在 AJAX 请求的 Success 方法中打开的 pdf 文档。
问题:
当我调用 WebApi url 时,我在 Chrome 的控制台中收到以下错误:
XMLHttpRequest cannot load http://xxxxxxx.azurewebsites.net/api/PdfHandler/PdfButtonCaller.
No 'Access-Control-Allow-Origin' header is present on the requested resource.
Origin 'http://localhost:1570' is therefore not allowed access.
The response had HTTP status code 405.
我已添加 Chrome Allow Control Origin Control 插件。
守则:
包含 AJAX 请求的 MVC 视图:
@{
ViewBag.Title = "PdfButtonCaller";
}
<script src="~/Scripts/jquery-1.8.2.min.js"></script>
<h2>PdfButtonCaller</h2>
<button id="pdfClick">Click this</button>
<script>
$(document).ready(function () {
$('#pdfClick').click(function () {
alert('clicked');
$.ajax({
type: "POST",
url: 'http://xxxxxxx.azurewebsites.net/api/PdfHandler/PdfButtonCaller',
cache: false,
contentType: 'application/pdf',
success: function (response) {
alert('worked');
window.open('http://xxxxxxx.azurewebsites.net/api/PdfHandler/GetPdf');
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert('Error'+ textStatus, errorThrown);
}
});
});
});
</script>
WebApi 控制器:
public class PdfHandlerController : ApiController
{
[System.Web.Http.HttpPost]
public void PdfButtonCaller()
{
var fullPath = System.Web.Hosting.HostingEnvironment.MapPath(@"~/App_Data/readme.pdf");
byte[] bytes = System.IO.File.ReadAllBytes(fullPath);
}
[System.Web.Http.HttpGet]
public HttpResponseMessage GetPdf()
{
var fullPath = System.Web.Hosting.HostingEnvironment.MapPath(@"~/App_Data/readme.pdf");
byte[] bytes = System.IO.File.ReadAllBytes(fullPath);
var response = new HttpResponseMessage(System.Net.HttpStatusCode.OK);
response.Content = new ByteArrayContent(bytes);
response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/pdf");
return response;
}
}
任何帮助解决此 XMLHttpRequest 请求错误将不胜感激。
【问题讨论】:
-
请在 StackOverflow 上快速搜索这个问题 - 这个问题已经回答了很多次了。
-
每天都会出现问题...谷歌该错误...您应该在此处发布问题之前完成此操作
-
了解同源策略和 CORS
标签: javascript jquery ajax asp.net-web-api