How to set custom host headers in xNet c# - c#

HttpRequest request = new HttpRequest();
request.AddHeader("Host", "api.dwebsir.com");
request.Proxy = ProxyClient.Parse(ProxyType.Http, proxy);
this way of adding custom host header doesnt seems to work.
When i ignore the the proxy and while posting without headers also seems to work.
But when i postdata with proxy and request.Header it is not taking and i am not getting any response
But when i postdata with proxy and i am receiving this The requested URL /as/token.oauth2 was not found on this server.
i am pretty sure the error is with Host as headers i am not getting the proper fix

There is a way to do this, as Explanation given here:
http://blogs.msdn.com/feroze_daud/archive/2005/03/31/404328.aspx
next version of the framework (.NET Framework 4.0) will make it easier.
http://blogs.msdn.com/ncl/archive/2009/07/20/new-ncl-features-in-net-4-0-beta-2.aspx
Hope this helps you.

Related

Strange Error 400 while using HttpRequest to consume REST API

I am trying to consume a REST API and i have an issue that it is driving me crazy...
I created a dll to wrap the service consumption layer, and i found that if i consume the services using the c# interactive feature it works fine.
The issue is when i try to consume it from another DLL, it is throwing Bad Request exception when executing GetResponse()
The code executed is...
var url = $"{_salesForceInstance}/services/data/{_salesForceVersion}/query/?q=SELECT+Id,Name,AccountId+from+Contact+WHERE+Email+=+'{email}'";
var webRequest = (HttpWebRequest)WebRequest.Create(url);
webRequest.ServicePoint.CloseConnectionGroup(webRequest.ConnectionGroupName);
webRequest.Method = "GET";
webRequest.ContentType = "application/json";
webRequest.Headers.Add("Authorization", $"Bearer {_authorizationToken}");
var webResponse = webRequest.GetResponse() as HttpWebResponse;
I also when debugging code, to send the same through POSTMAN and it works fine...
Any ideas??? I am quite frustrated at this point why it works when consuming the dll from C# interactive but not from another dll...
As spender suggested i tried with Fiddler...
I found that despite of the fact both request looks the same, (the one from c# interactive and the one from the console app), in the one that returned the HTTP 400 error code the response included the following message
"[{"message":"TLS 1.0 has been disabled in this organization. Please use TLS 1.1 or higher when connecting to Salesforce using https.","errorCode":"UNSUPPORTED_CLIENT"}]"
That message does not appear when debugging...
Finally i solved by including the line described below in my code in order to use TLS 1.2
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
Now it works !!!
Hope this helps to someone else!
Thanks!

WCF + NUnit: Unsupported Media Type

I am currently struggling with a very unusual behavior with WCF.
I created a REST endpoint to use with my application, manually tested it out using curl and everything seems to be fine, until I tried to write NUnit tests for it.
The content of my test is basically creating a HttpWebRequest and hit it on my api. Whenever I run the test I get the following error
UnsupportedMediaType Cannot process the message because the content type
'application/json;charset=utf-8;' was not the expected type 'text/xml;
charset=utf-8'.
I have searched for answers, almost all of them is related to mis-configured service, however that cant be the case since a curl request will work.
None explains how come the endpoint only fails with this setup.
Any help would be appreciated
When you send the request you need to specify the type of content. Try this -
HttpWebRequest request = ...
request.ContentType = "text/xml; charset=utf-8";
Also make sure that you are sending XML and not JSON content.

Rest Sharp - 406 Error - No match for accept header

I'm getting a 406 error when trying to use RestSharp to post a request to a third-party application. I'm new to REST, so I have to admit I didn't even know you could add headers. I tried adding these, but I'm still getting the same issue:
var client = new RestClient(myURL);
RestRequest request = new RestRequest("restAction", Method.POST);
request.AddHeader("Accept", "text/plain");
request.AddHeader("Content-Type", "text/plain");
request.AddParameter("parameter1", param1);
request.AddParameter("parameter2", param2);
var response = client.Execute(request);
From what I've read, this may be dealing with a header named "accept". Is that right?
Any idea what could be going on?
In general in HTTP, when a client makes a request to a server, it tells the server what kinds of formats it's prepared to understand (accept). This list of acceptable formats is what the Accept header is for. If the server can't respond using any of the media types in the Accept header, it will return a 406. Otherwise, it will indicate which media type it chose in the Content-Type header of the response. Putting "*/*" in the Accept header tells the server that the client can handle any response media type.
In my original comment to your question, I said that RestSharp looks like it's including "*" in the Accept header by default, but looking closer I see now that it's actually not. So, if you don't override the Accept header like you've done here, the default header value is "application/json","application/xml","text/json","text/x-json","text/javascript","text/xml", and it appears the server you're talking to doesn't speak any of these media types.
If the server you're working with doesn't speak json or xml, I don't think you can use RestSharp, unless you create your own deserializer. I'm not sure if you can do this from the public API or if you'd have to modify the source yourself and recompile it for you own needs.
Since you're still getting HTTP errors from the server, I would recommend taking RestSharp out of the equation for right now, and just speaking HTTP directly to the server until you actually get a correct response from the server. You can use a tool like Fiddler to make a HTTP requests directly. When you send the request (for now in the debugging stage), send an Accept header of "*/*" to get around the 406. Once you've figured out what media types the server can send back to you, you should change this back to being a media type you know you can read and you know the server can send.
It sounds like the main issue here is really just not knowing the protocol of the server. If there's any documentation on the service you're talking to, I would read that very carefully to figure out what media types it's prepared to respond with and how to craft the URLs that it expects.

How to edit request host headers in c# through web request?

When i'm trying to edit the Host key on Request.Headers under console application i'm getting exception that says:
The 'Host' header cannot be modified directly.
Parameter name: name
So how can i change it?
As you've seen the .Net Fx does not allow to edit the host header, but since .Net Fx 4.0 there is a seperate 'Host' definition on the HttpWebRequest object. You can use it like this:
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://127.0.0.1/");
request.Host = "yourdomain.com";
Hope that helps you out.

HTTP library that doesn't depend on HttpWebRequest

I need a C# HTTP library that doesn't depend on HttpWebRequest, as I can't access this from the environment I need to run my code (Unity's WebPlayer).
Ideally this would be light weight, but any suggestions are welcome!
I just need to be able to do simple HTTP GET and POST requests, but better REST support would be good.
Thanks!
Edit: As people have pointed out, HttpWebRequest isn't in System.Web, but the fact remains - I can't use it. I've updated my post above.
This post
http://forum.unity3d.com/threads/24445-NotSupportedException-System.Net.WebRequest.GetCreator shows the same error I'm getting.
Implementing your own simple HTTP client using Socket is not all that difficult.
Just use TcpClient().
For the protocol itself, drop down to a connection-per-request paradigm. A typical GET request would look as follows:
GET /url HTTP/1.1
Host: <hostname-of-server>
Connection: close
For the code itself (from memory)
TcpClient client = new TcpClient();
IPEndPoint target = ... // get an endpoint for the target using DNS class
client.Connect(target);
using(NetworkStream stream = client.GetStream())
{
// send the request.
string request = "GET /url HTTP/1.1\r\nConnection: close\r\n\r\n";
stream.Write(Encoding.ASCII.GetBytes(request));
// then drain the stream to get the server response
}
Note that you will need to wrap this code with a simple class that provides HTTPWebRequest like semantics.
Look at System.Net.HttpWebRequest.
It is in System.dll.
Documentation: http://msdn.microsoft.com/en-us/library/system.net.httpwebrequest.aspx
HttpRequest is located in System.Web, which is probably what you were thinking of.
HttpWebRequest is in the System assembly, not in System.Web (perhaps you're confusing with HttpRequest which is used in ASP.NET). It is available in all .NET Framework versions (including Silverlight, WP7, and Client Profile)

Categories

Resources