IE10没有将CORS请求的Origin Header添加到具有相同主机路径但具有不同端口的域#

时间:2013-06-26 00:24:09

标签: api http-headers cross-domain cors self-hosting

这让我绝对疯狂。我已经破解了自托管WebAPI服务器和MVC4客户端的基本实现。它们位于不同的解决方案中,并设置为在不同的端口上运行。 CORS请求在我前几天测试(IE10 / FF / Chrome)的浏览器中运行良好,但现在突然IE10已停止向请求添加Origin标头。我现在正在家庭计算机上遇到这个简单的例子,以及我在工作中正在实施的实现。

我已经尝试过在Google搜索中我能想到的每一个组合,看看是否有其他人遇到过此问题,并且发现了一个解决方案。我最接近的是Microsoft Connect的反馈链接,但仍未解决。

我尝试过更换端口,制作全新的项目,清除浏览器缓存;你说它,我已经尝试过了(除了最后工作,显然!)。

以下是使用Firefox的Get请求的请求标头: 注意:我必须为链接

中的localhost的Referer和Origin标题b / c添加空格
  

主持人:localhost:60000

     

User-Agent:Mozilla / 5.0(Windows NT 6.1; WOW64; rv:21.0)Gecko / 20100101 Firefox / 21.0

     

接受:application / json,text / javascript, / ; Q = 0.01

     

接受语言:en-US,en; q = 0.5

     

Accept-Encoding:gzip,deflate

     

Referer:http:// localhost:50954 /

     

原产地:http:// localhost:50954

     

连接:保持活力

以下是使用IE10的相同Get请求的请求标头:

  

Referer:http:// localhost:50954 /

     

接受:application / json,text / javascript, / ; Q = 0.01

     

接受语言:en-US

     

Accept-Encoding:gzip,deflate

     

User-Agent:Mozilla / 5.0(兼容; MSIE 10.0; Windows NT 6.1; WOW64; Trident / 6.0)

     

连接:Keep-Alive

     

DNT:1

     

主持人:localhost: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示例的相关类:

Program.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();
    }
}

EmployeesController.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上&gt;。&lt;

0 个答案:

没有答案