WebRequest will not pass headers when used from within ASP.NET MVC controller

半世苍凉 提交于 2019-12-11 19:58:04

问题


I have an ASP.NET MVC 4 project that when I make an http call using a webrequest, the headers will not pass.

The same code in Linqpad I can set info in the headers such as AUTHORIZATION and it works fine (I can see the header values in Fiddler)

However, when I do the same code from within my MCV controller then the headers do not pass. Its as if ASP.NET MVC is overriding my headers.

Any suggestions?

        var client = WebRequest.Create(url);
        client.Headers.Add(String.Format("Authorization:{0}", "Fun-Kitty"));
        client.Headers.Add(String.Format("X-Requested-With:{0}", "PowerFlower"));
        client.Method = "GET";
        client.ContentType = "application/json";

        HttpWebResponse resp;
        using (resp = (HttpWebResponse)client.GetResponse())
        {
            if (resp.GetResponseStream() != null)
            {
                var status = resp.StatusDescription; // TODO
                var reader = new StreamReader(resp.GetResponseStream());
                var obj = reader.ReadToEnd();
            }
        }

UPDATE: Please note that the headers are setting correctly (except when called from with MVC Controller) - setting the header various ways has no impact (ie: works in Linqpad, not in MVC Controller)

    client.Headers.Set("Authorization", "PwrUp");
    client.Headers["Authorization"] = "ababab11ab";
    client.Headers.Add(String.Format("Authorization:{0}", "Fun-Kitty"));

This code passes the headers just fine from LinqPad or a Winforms/WPF App BUT NOT from ASP.NET MVC Controller.

I also notice when inspecting the header that when the call is made from the MVC controller, the following value is set (not sure if it has anything to do with it though):

X-Requested-With: XMLHttpRequest

回答1:


I believe you need to remove the white space on the right side of the : on your header adds:

client.Headers.Add(String.Format("Authorization:{0}", "Fun-Kitty"));
client.Headers.Add(String.Format("X-Requested-With:{0}", "PowerFlower"));

Alternatively, use the overload that takes 2 string parameters:

client.Headers.Add("Authorization", "Fun-Kitty");
client.Headers.Add("X-Requested-With", "PowerFlower");

Per the MSDN docs:

The header parameter must be specified in the format "name:value".



来源:https://stackoverflow.com/questions/27022647/webrequest-will-not-pass-headers-when-used-from-within-asp-net-mvc-controller

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!