这让我彻底疯了。我已经破解了自托管 WebAPI 服务器和 MVC4 客户端的基本实现。它们位于不同的解决方案中,并设置为在不同的端口上运行。CORS 请求在我前几天测试的浏览器(IE10/FF/Chrome)中运行良好,但现在 IE10 突然停止将 Origin 标头添加到请求中。我现在正在我的家用电脑上体验这个小例子,以及我正在工作的实现。
我已经尝试了在谷歌搜索中我能想到的所有组合,看看其他人是否正在经历这种情况并找到了解决方案。我最接近的是this link to feedback on Microsoft Connect,但仍未解决。
我尝试过更改端口,制作全新的项目,清除浏览器缓存;你说出它的名字,我已经尝试过了(显然,除了最终工作的任何东西!)。
以下是使用 Firefox 的 Get 请求的请求标头: 注意:我必须在链接中为 localhost 的限制的 Referer 和 Origin 标头 b/c 添加空格
主机:本地主机:60000
用户代理:Mozilla/5.0 (Windows NT 6.1; WOW64; rv:21.0) Gecko/20100101 Firefox/21.0
接受:应用程序/json、文本/javascript、/;q=0.01
接受语言:en-US,en;q=0.5
接受编码:gzip,放气
参考:http://localhost:50954/
来源:http://localhost:50954
连接:保持活动
以下是使用 IE10 的同一 Get 请求的请求标头:
参考:http://localhost:50954/
接受:应用程序/json、文本/javascript、/;q=0.01
接受语言:en-US
接受编码:gzip,放气
用户代理:Mozilla/5.0(兼容;MSIE 10.0;Windows NT 6.1;WOW64;Trident/6.0)
连接:保持活动
DNT: 1
主机:本地主机:60000
对于其他 HTTP 方法,IE10 中也省略了 Origin 标头。
这是示例 MVC4 应用程序的相关代码:
主页/Index.cshtml:
@section scripts
{
<script type="text/javascript">
$(document).ready(function () {
$('#details').click(function () {
$('#employee').empty();
$.getJSON("http://localhost:60000/api/employees/12345", function (employee) {
var now = new Date();
var ts = now.getHours() + ':' + now.getMinutes() + ':' + now.getSeconds();
var content = employee.Id + ' ' + employee.Name;
content = content + ' ' + employee.Department + ' ' + ts;
$('#employee').append($('<li/>', { text: content }));
})
});
$('#update').click(function () {
$('#employee').empty();
$.ajax({
type: 'PUT',
url: "http://localhost:60000/api/employees/12345",
data: { 'Name': 'Beansock', 'Department': 'Nucular Strategory' },
success: function (employee) {
var now = new Date();
var ts = now.getHours() + ':' + now.getMinutes() + ':' + now.getSeconds();
var content = employee.Id + ' ' + employee.Name;
content = content + ' ' + employee.Department + ' ' + ts;
$('#employee').append($('<li/>', { text: content }));
},
error: function (error) {
console.log('Error:', error);
}
});
});
});
</script>
}
<div>
<div>
<h1>Employees Listing</h1>
<input id="search" type="button" value="Get" />
<input id="details" type="button" value="Details" />
<input id="update" type="button" value="Update" />
</div>
<div>
<ul id="employees"></ul>
</div>
<div>
<ul id="employee"></ul>
</div>
</div>
以下是自托管 WebAPI 示例中的相关类:
程序.cs
class Program
{
private static readonly Uri Address = new Uri("http://localhost:60000");
static void Main(string[] args)
{
HttpSelfHostServer server = null;
HttpSelfHostConfiguration config = null;
// create new config
config = new HttpSelfHostConfiguration(Address) { HostNameComparisonMode = HostNameComparisonMode.Exact };
// set up routing
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional });
// set up handlers
config.MessageHandlers.Add(new CorsHandler());
// create server
server = new HttpSelfHostServer(config);
server.OpenAsync().Wait();
Console.WriteLine("Server is up and running.");
Console.ReadLine();
}
}
雇员控制器.cs
public class EmployeesController : ApiController
{
public HttpResponseMessage Get(int id)
{
var employee = new Employee()
{
Id = id,
Name = "Chucky Chucky Chuck",
Department = "Profreshies"
};
var response = Request.CreateResponse<Employee>(HttpStatusCode.OK, employee);
return response;
}
public HttpResponseMessage Put(Employee emp)
{
//employee2 = emp;
var response = Request.CreateResponse<Employee>(HttpStatusCode.OK, emp);
return response;
}
Employee employee2 = new Employee()
{
Id = 12345,
Name = "Jimmy John John",
Department = "Slow Lorisesssessss"
};
}
internal class Employee
{
public int Id { get; set; }
public string Name { get; set; }
public string Department { get; set; }
}
CorsHandler.cs
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
// if the request is coming from a browser supporting CORS
if (request.Headers.Contains("Origin"))
{
// if the Request Origin does not match a server list of valid origins, or
// if the Request Host does not match the name of this server (to help prevent DNS rebinding attacks)
// return a 403 Forbidden Status Code
var origin = request.Headers.GetValues("Origin").FirstOrDefault();
var host = request.Headers.GetValues("Host").FirstOrDefault();
if (validOrigins.Contains(origin) == false || !host.Equals(validHost))
return Task<HttpResponseMessage>.Factory.StartNew(() => new HttpResponseMessage(HttpStatusCode.Forbidden));
// if the Request is not a simple one, IE: POST, PUT, DELETE, then handle it through an OPTIONS Preflight
if (request.Method == HttpMethod.Options)
{
var methodRequested = request.Headers.GetValues("Access-Control-Request-Method").FirstOrDefault();
var response = new HttpResponseMessage(HttpStatusCode.OK);
response.Headers.Add("Access-Control-Allow-Origin", origin);
response.Headers.Add("Access-Control-Allow-Methods", methodRequested);
return Task<HttpResponseMessage>.Factory.StartNew(() => response);
}
else // if Request is a GET or HEAD, or if it has otherwise passed the Preflight test, execute here
{
return base.SendAsync(request, cancellationToken)
.ContinueWith((task) =>
{
var response = task.Result;
response.Headers.Add("Access-Control-Allow-Origin", origin);
return response;
});
}
}
return base.SendAsync(request, cancellationToken)
.ContinueWith((task) => task.Result);
}
private IList<string> validOrigins = new List<string>() { "http://localhost:50954" };
private string validHost = "localhost:60000";
}
我认为这应该是您重新创建场景所需的全部内容。某处的代码有问题吗?在确定它是否是跨域请求时,IE10 是否通过忽略端口号来正确实施 CORS 规范?DoNotTrack 默认为 ENABLED 是否与此有关?我可以发誓前几天我的工作正常......对此的任何见解将不胜感激。提前致谢。顺便说一句,是的,我知道我可以使用 async/await,除了我不能,因为在工作中我们仍然使用 Windows Server 2003 >.<