问题
i have trolled and tried everything, i have done this 100's of times before without issues but now im stumped.
I simply want to pass header info from a webrequest.
The client runs separately and connects to a wcf rest service. The service has this code which gets hit:
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Headers", "Authorization, Origin, Content-Type, Accept, X-Requested-With");
The client has this:
var client = WebRequest.Create(url);
client.Method = type.ToString().ToUpper();
client.ContentType = "application/json";
client.ContentLength = bytes.Length;
client.Headers.Add(String.Format("Authorization: {0}", "test12345"));
I have also tried for example:
client.Headers["X-Requested-With"] = "test1234";
client.Headers["Authorization"] = "test1234";
No matter how i try and set the headers they are never passed. When I look at the request in fiddler, Authorization is NEVER there. I have also tried to send X-Requested-With, etc... but no matter what the header will not pass.
Thanks in advance.
UPDATE: I found the issue, but not the solutions: WebRequest will not pass headers when used from within ASP.NET MVC controller
回答1:
Does the server require authentication? According to this answer the WebRequest will not send credentials until challenged. If you want to send it regardless you may need to use a different class than WebRequest
to send the request, eg RestSharp
回答2:
Instead of using WebRequest you can use RestSharp. It has a simple abstraction and API.
回答3:
I know that it is maybe a little too late (found this when looking for some answers to my question).
Don't know if it will help you, but mine is like this and I have the Authorization header in the server side and I'm using 4.5.1.
Client Side
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
req.Headers[HttpRequestHeader.Authorization] = "basic " +
Convert.ToBase64String(
Encoding.ASCII.GetBytes(
string.Format("{0}|{1}", "login", "password")));
string result = string.Empty;
using (WebResponse resp = (HttpWebResponse)req.GetResponse())
{
using (StreamReader sr = new StreamReader(resp.GetResponseStream()))
{
result = sr.ReadToEnd();
}
}
Server side
WebOperationContext.Current.IncomingRequest.Headers[HttpRequestHeader.Authorization]
回答4:
Use DefaultRequestHeaders
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("test12345")
来源:https://stackoverflow.com/questions/27005799/webrequest-will-not-pass-headers