【发布时间】:2014-01-27 08:19:47
【问题描述】:
我正在尝试使用 jQuery 的 ajax() 函数进行简单的 Web api 调用。我有一个授权令牌,我需要将其传递给标头中的 api 方法。 Web api 方法工作正常,因为我在 POSTMAN(一个 chrome 应用程序)中对其进行了测试。在 POSTMAN 中,我使用以下设置:
URL: http://api.mycompany.com/v1/marketsegments/
Type: GET
Authorization: 32asd1sadf4sa5d6a4sd5as64
我点击发送按钮,然后我取回了我需要的数据。
我在 Visual Studio 2013 中创建了一个小型 Web 应用程序。当我运行该项目并使用 IE10 时,我收到以下错误:
SEC7118: XMLHttpRequest for http://api.mycompany.com/v1/marketsegments/ required Cross Origin Resource Sharing (CORS).
SEC7119: XMLHttpRequest for http://api.mycompany.com/v1/marketsegments/ required CORS preflight.
我认为这里描述了我所经历的:
jQuery, CORS, JSON (without padding) and authentication issues
但是,我没有可以遵循的解决方案。
我检查了堆栈上的很多材料,但我不确定我需要做什么才能使 ajax() 函数正常工作。我查看了以下链接,但没有任何效果:
http://api.jquery.com/jQuery.ajax/
http://api.jquery.com/jQuery.get/
Sending credentials with cross-domain posts?
Unable to send a CORS POST request with jQuery
http://www.html5rocks.com/en/tutorials/cors/#toc-cors-from-jquery
CORS - How do 'preflight' an httprequest?
A CORS POST request works from plain javascript, but why not with jQuery?
How to get a cross-origin resource sharing (CORS) post request working
Cross Origin Resource Sharing - CORS
using jQuery post to ASP.Net webapi
Web API Put Request generates an Http 405 Method Not Allowed error
405 method not allowed web api
Web API Put Request generates an Http 405 Method Not Allowed error
Access-Control-Allow-Origin Multiple Origin Domains?
HTTPListener "credentials flag" lie
CORS $.ajax session cookies (access-control-allow-credentials & withCredentials=true)
CORS: Cannot use wildcard in Access-Control-Allow-Origin when credentials flag is true
Ajax NetworkError: A network error occurred
What causes an HTTP 405 "invalid method (HTTP verb)" error when POSTing a form to PHP on IIS?
http://praneeth4victory.wordpress.com/2011/09/29/405-method-not-allowed/
Post data to RESTful Invalid HTTP status code 405
http://www.codeproject.com/Articles/424461/Implementing-Consuming-ASP-NET-WEB-API-from-JQuery
How to use Basic Auth with jQuery and AJAX?
Consuming authorized asp.net webapi service using jQuery ajax
这是客户端代码:
<!DOCTYPE html>
<html>
<head>
<title>Index</title>
<script src="scripts/jquery.min.js"></script>
<script>
$(document).ready(function () {
var token = '32asd1sadf4sa5d6a4sd5as64';
var $div1 = $('#div1');
$.ajax({
contentType: 'application/x-www-form-urlencoded',
type: 'POST',
dataType: 'json',
url: 'http://api.mycompany.com/v1/marketsegments/',
xhrFields: {
withCredentials: true
},
beforeSend: function (jqXhr) {
jqXhr.setRequestHeader('Authorization', token);
}
}).done(function (response) {
$div1.html(response);
}).fail(function (response) {
$div1.html(response.statusText);
});
/*
This code doesn't work, but I've tried all variations of it using the recommendations from the links above.
$.ajax({
contentType: 'application/json',
type: 'GET',
dataType: 'json',
crossDomain: true,
url: 'http://api.mycompnay.com/v1/marketsegments/',
headers: {
"X-Requested-With": "XMLHttpRequest"
},
xhrFields: {
withCredentials: true
},
beforeSend: function (jqXHR) {
jqXHR.setRequestHeader('Authorization', token);
}
}).done(function (response) {
$div1.html(response);
}).fail(function (response) {
$div1.html(response.statusText);
});
*/
});
</script>
</head>
<body>
<div id="div1"></div>
</body>
</html>
这里是web api方法:
[HttpGet]
[Route("v1/marketsegments")]
public HttpResponseMessage MarketSegments()
{
var token = Request.Headers.Authorization.ToString();
try
{
// Check token here...
// Return the response.
return Request.CreateResponse(HttpStatusCode.OK, marketSegments, JsonMediaTypeFormatter.DefaultMediaType);
}
catch (Exception ex)
{
return Request.CreateResponse(HttpStatusCode.InternalServerError, ex.Message);
}
}
这是我的 web.config 文件:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<system.web>
<compilation debug="true" targetFramework="4.5" />
<httpRuntime targetFramework="4.5" />
</system.web>
<system.webServer>
<httpProtocol>
<customHeaders>
<clear />
<add name="Access-Control-Allow-Origin" value="*" />
</customHeaders>
</httpProtocol>
</system.webServer>
</configuration>
【问题讨论】:
标签: javascript jquery ajax asp.net-web-api