I have a problem when I do an httprequest and the remote server responds with a redirect and some additional query parameters. The problem is that the additional parameters is empty on certain enviroments.
When I run the code in a test-environment the parameters is not empty.
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
WebProxy myProxy = new WebProxy();
Uri newUri = new Uri(ConfigurationManager.AppSettings["proxyUrl"]);
myProxy.Address = newUri;
request.Proxy = myProxy;
request.Timeout = Int32.Parse(ConfigurationManager.AppSettings["PBVtimeout"]);
request.AllowAutoRedirect = true;
request.MaximumAutomaticRedirections = 2;
ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(myCertificateValidation);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
log.Debug("PathAndQuery: " + response.ResponseUri.PathAndQuery);
log.Debug("Statuscode: " + response.StatusCode);
log.Debug("Statusdescription: " + response.StatusDescription);
Uri uri = response.ResponseUri;
NameValueCollection qscol = ParseQueryString(uri.Query);
return qscol["Status"] + qscol["Status_code"];
I log StatusCode, StatusDescription and the PathAndQuery of the response. StatusCode and StatusDescription is "OK" in both enviroments but the PathAndQuery looks like this:
Faulty environment: localhost/Service
Correct environment: localhost/Service?Merchant_id=1345&Version=2&Customer_refno=269932&Status=E&Status_code=48
As you can see the faulty enviroments is missing the parameters.
My initial thought was that it was a problem with a firewall "cleaning" the redirect response. But when I did the http request in an ordninary web browser it worked fine.
The code is in C# .Net 2.0 and it runs on a Windows 2003 server.
Any ideas where the problem could be?
Related
I have been trying to make a post request with C# using Webclient. I was getting 400 bad request.When I adjusted the headers, and added authorization to it,I started getting 401 authorization error.Now i commented out the authorization, 400 bad request is back. So my question is: when it was returning 400, does it mean the server authenticated me and that something might be wrong with my json or can 400 be returned even before authentication is done? Below is my code.
public static string Post(string json, string encoded){
try{
string url = "https://blah/rest/api/blah";
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
var client = new WebClient();
client.Encoding = Encoding.UTF8;
IWebProxy wp = WebRequest.DefaultWebProxy;
wp.Credentials = CredentialCache.DefaultCredentials;
client.Proxy = wp;
//client.Headers[HttpRequestHeader.Authorization] = "Basic " + encoded;
client.Headers[HttpRequestHeader.ContentType] = "application/json";
client.Headers[HttpRequestHeader.Accept] = "application/json";
var response = client.UploadString(url, "POST",json);
return response
}
catch(Exception e){
return e
}
}
This is my C# code:
var url = "http://10.2.0.2/api";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Referer = url;
request.Host = "wwww.abc.com";
request.Accept = "*/*";
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
while I run the code, and open fiddler to capture request,
I found fiddler discard header: Host,
so my IIS returned an error!
How did I avoid it?
Why fiddler discards Host but keep other headers?
Question: another
was header be changed, my question was header be discard.
I found my solution, open FiddlerScript, and add these script:
static function OnBeforeRequest(oSession: Session) {
var sOverride = oSession["X-Original-Host"];
if (!String.IsNullOrEmpty(sOverride))
{
oSession.oRequest.headers["Host"] = sOverride;
}
I need to consume web service that requires basic pre-emptive authentication. I have below code, but getting an error on response -
'The remote server returned an error: (403) Forbidden.'
User credentials are correct. Any ideas what is wrong?
string url = "MYURL";
HttpWebRequest req = HttpWebRequest.Create(url) as HttpWebRequest;
string user = "USER";
string pwd = "PASSWORD";
string auth = "Basic " + Convert.ToBase64String(System.Text.Encoding.Default.GetBytes(user + ":" + pwd));
req.PreAuthenticate = true;
req.AuthenticationLevel = System.Net.Security.AuthenticationLevel.MutualAuthRequested;
req.Headers.Add("Authorization", auth);
WebResponse resp = req.GetResponse();
resp.Close();
req = HttpWebRequest.Create(url) as HttpWebRequest;
req.PreAuthenticate = true;
req.Credentials = new NetworkCredential(user, pwd);
resp.Close();
401 is the error code you receive when you could not be authenticated (i.e. it's unclear who you are). If you get a 403 that means the server knows who you are but still thinks you should not be allowed access.
I guess you should talk to whoever provided you with the credentials and ask him.
I'm using Basic Authentication to retrieve xml order information from a website. The website endpoint url receives the authentication and then redirects to an url with the order information. I can successfully authenticate but not retrieve the order information (I get a blank page, with status 200. NOTE: This is the same result I get in a browser if I navigate directly to the redirected url without first go to the url which handles authentication). I believe this is because I need to handle the authentication cookie. However, as soon as I add a cookie container to my request, request.GetResponse() bombs with an internal server error 500.
I have tested the url endpoint using Fiddler, and I get the same result as when I don't add a cookie container to my request. Authentication is successful, and then the redirected page is blank with status code 200. (P.S. I can tell from Fiddler that the cookie is HttpOnly)
However, if I use a web browser and enter credentials at the initial url, it redirects to the order page with order content displayed.
Question 1: How can I determine (or further troubleshoot) if this is a problem with my code or with the order endpoint?
Question 2: If it's a problem with my code, how should I handle the cookie?
My code:
public void Main()
{
Uri endpointUri = new Uri(Dts.Variables["User::endpointUrl"].Value.ToString());
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(endpointUri);
request.Method = "GET"; //I have also tried POST
request.KeepAlive = true;
request.AllowAutoRedirect = true;
request.MaximumAutomaticRedirections = 1;
SetBasicAuthHeader(request, Dts.Variables["User::endpointUsername"].Value.ToString(), Dts.Variables["User::endpointPassword"].Value.ToString());
request.CookieContainer = new CookieContainer(); //If I comment out this line, the error does not occur, but I also don't see any order info.
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
Stream dataStream = response.GetResponseStream();
Debug.WriteLine((new System.IO.StreamReader(dataStream)).ReadToEnd());
return;
}
}
public void SetBasicAuthHeader(WebRequest req, String userName, String userPassword)
{
string authInfo = System.Convert.ToBase64String(System.Text.Encoding.GetEncoding("ISO-8859-1").GetBytes(userName + ":" + userPassword));
req.Headers["Authorization"] = "Basic " + authInfo;
}
The error:
The remote server returned an error: (500) Internal Server Error at
System.Net.HttpWebRequest.GetResponse()
I am looking to create a C# application that will report on the connections that we make to customers. I am looking into the TeamViewer API, but I cannot get the code below to authenticate:
string accessToken = "xxxxxxxxxxxxxxxxxxx";
string apiVersion = "v1";
string tvApiBaseUrl = "https://webapi.teamviewer.com";
string address = tvApiBaseUrl + "/api/" + apiVersion + "/reports/connections";
try
{
// Create the web request
HttpWebRequest request = WebRequest.Create(address) as HttpWebRequest;
request.Headers.Add("Bearer", accessToken);
request.Method = "GET";
WebResponse webResp = request.GetResponse();
}
catch (Exception)
{
// Do nothing for now
}
Use fiddler and make sure your requests include the authorization header.
All API requests need to include the "Authorization" header if the API function requires an access token.
Example
GET /api/v1/users HTTP/1.1
Host: webapi.teamviewer.com
Authorization: Bearer 54213-2YotnFZFEjr1zCsicMWp
Also examine what they are sending you back, it may provide a clue.
UPDATE
Try this change
request.Headers.Add("Authorization", "Bearer " + accessToken);