Avoid HttpWebRequest GET and ProtocolViolationException - httpwebrequest

Is there anyway to prevent HttpWebRequest.GetRequestStream from throwing an exception when the method is GET? I know that HEAD and GET should not contain a body in valid HTTP, but some servers accept bodies for these methods anyway (e.g., Elasticsearch's _search feature). I have an open source project for doing REST calls and I was wondering if I could circumvent this behavior to avoid surprises.
At some point, I will probably create a version of my library using the new System.Net.Http.HttpClient class. Does this class have the same restrictions?

.Net Core 2.0:
System.Net.Http.HttpClient (Version=4.2.0.0) does not have this restriction if you use the SendAsync method.
var request = new HttpRequestMessage(HttpMethod.Get, "http://example.com/api/_search");
request.Content = new StringContent(jsonSearchCriteria, Encoding.UTF8, "application/json");
var response = await httpClient.SendAsync(request,
HttpCompletionOption.ResponseContentRead);
var jsonResponse = await response.Content.ReadAsStringAsync();

Related

Post request error when sending "application/octet-stream" to an ASP.NET Core Web API service

I need to create an ASP.NET Core 3 Web API that understand this URL
http://myapp.com/MyASPNetCore3WebApi/myController/myWebMethod?user=A0001
and one zipfile which goes as a content. This is the code that calls the needed API, which I need to create:
HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(URI);
httpWebRequest.Timeout = -1;
httpWebRequest.KeepAlive = false;
httpWebRequest.Method = "POST";
httpWebRequest.ProtocolVersion = HttpVersion.Version10;
httpWebRequest.ContentType = "application/octet-stream";
httpWebRequest.Accept = "application/octet-stream";
httpWebRequest.ContentLength = data.Length;
Stream requestStream = httpWebRequest.GetRequestStream();
requestStream.Write(data, 0, data.Length);
requestStream.Close();
HttpWebResponse httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse();
The code above is working fine, it is used everyday, sending data to a java web service, now I am replacing that system for a new one in ASP.NET Core and I can't change the caller's code, that's why I need to create a Web API that understand that URL.
I have wrote this code in my Web API, but I guess I am missing something that I canĀ“t figure it out because I get an error ion the client (code above)
[HttpPost("myWebMethod")]
public FileStreamResult myWebMethod(string user, [FromBody] Stream compress)
{
byte[] zip = ((MemoryStream)compress).ToArray();
byte[] data = ZipHelper.Uncompress(zip);
.....................
}
The error I get in the client is this:-
[System.Net.WebException] {"The remote server returned an error: (415)
Unsupported Media Type."} System.Net.WebException
Thanks in advance for any help
If the goal is to read the raw request content, this can be done using HttpContext controller property. HttpContext has Request property that provides access to the actual HTTP request.
No additional model properties or controller arguments are needed to access raw request stream. It's important to note that FromBody and FromForm binding should not be used in this case.
There are couple notes regarding the code in the example from the original question.
byte[] zip = ((MemoryStream)compress).ToArray();
byte[] data = ZipHelper.Uncompress(zip);
The HttpContext.Request.Body property does not return MemoryStream, it returns its own implementation of a Stream. It means that there is no ToArray method.
When reading the entire content of a request directly into the server's memory, it is better to check the content length, otherwise the client can crash the server by sending a large enough request.
Using *Async methods when reading the content of the request will improve performance.

NetCore 3.1 PostAsync CustomHeaders not working

I have several RESTful services that working with each other. In one scenario I want to post some data from one service to another service and I want to attach some information in Header of the request. I saw several cases to do this and in the end I came up with this workaround:
var httpClient = new HttpClient();
httpClient.Timeout = TimeSpan.FromMinutes(3);
var httpRequestMessage = new HttpRequestMessage {
Method = HttpMethod.Post,
RequestUri = new Uri(service2Address),
Content = new StringContent(JsonConvert.SerializeObject(obj))
};
httpRequestMessage.Headers.Add("myCustomHeaderKey", "myCustomHeaderValue");
var response = await httpClient.SendAsync(httpRequestMessage);
var responseString = await response.Content.ReadAsStringAsync();
With these lines of code, a Post request sent, but in service2 when I want to get the headers from request, there is no sign of myCustomHeaderKey in headers collection. I inspect Request.Headers in Visual Studio Watch and even try to get custom header with Request.Headers["myCustomHeaderKey"]. So what's wrong here?
EDIT 1
This implementation in based on this tutorial.
I have developed code like yours. Have created Two Asp.net core 3.1 project with standart template. One service is starting localhost:44320 and other localhost:44300
localhost:44320/PostService wrote the your codes.
Then get this url with browser. localhost:44320/weatherforecast/IncomeService function is like below
Finally i put breakpoint to where get request header. Result is like below
There is a not a problem. Maybe you use change request header middleware. Or if you are using something like nginx. this problem maybe nginx configuration.

HttpRequestMessage.Content is null in receiving Controller action

I've looked at some similar posts, but all had some relevant detail that does not apply in my case. I have an existing Shopper service with a Register method. It is built on .NET Framework 4.6.1 Web API. I have a number of working scenarios in which another .NET Framework 4.6.1 Web API service calls the Shopper service using HttpClient and HttpRequestMessage. I do this with GET, PUT, and POST methods and successfully pass data to the PUT and POST methods using
request.Content = new ObjectContent<MemberAddress>(memberAddress, new System.Net.Http.Formatting.JsonMediaTypeFormatter());
I'm now developing a new service, this one built on ASP.NET Core Web API. I'm attempting to call a POST action in the Shopper service. I'm getting my HttpClient from IHttpClientFactory.CreateClient. The HttpRequestMessage set up is, I think, the same as in my other calling services.
var request = new HttpRequestMessage(HttpMethod.Post, updateShopperUrl);
request.Content = new ObjectContent<MemberRegistration>(memberRegistration, new System.Net.Http.Formatting.JsonMediaTypeFormatter(), "application/json");
The call to the service looks like this:
var httpClient = _clientFactory.CreateClient();
var response = await httpClient.SendAsync(request);
I can inspect request.Content.Value before the call and it contains the object/data I expect. The controller action code on the other end looks like this:
[Route("{shopperId}/register")]
[Route("~/api/shopper/{shopperId}/register")]
[HttpPost]
public IHttpActionResult RegisterNewMember(string shopperId, [FromBody] MemberRegistration memberRegistration)
{
But the memberRegistration parameter is always null. The [FromBody] attribute is recent addition in an attempt to solve this problem, but it did not help. FromBody should be the default behavior for a complex object parameter anyway. I can POST to that endpoint with Postman and the memberRegistration data comes through.
Either I'm just missing something obvious or maybe there's something different happening in the ASP.NET Core calling side of the equation.
It appears you are trying to post JSON data
Try changing the approach a bit and see if it make a difference.
var json = JsonConvert.SerializeObject(memberRegistration);
var content = new StringContent(json, Encoding.UTF8,"application/json");
var httpClient = _clientFactory.CreateClient();
var response = await httpClient.PostAsync(updateShopperUrl, content);
The above manually serializes the object to JSON and Posts it to the web API.
It is possible there could have been an issue with the formatter used with the ObjectContent

.NET HttpClient hangs after several requests (unless Fiddler is active)

I am using System.Net.Http.HttpClient to post a sequence of requests from a console application to a REST API and to deserialize the JSON responses into strongly-typed objects. My implementation is like this:
using (var client = new HttpClient())
{
var content = new StringContent(data, Encoding.UTF8, "text/html");
var response = client.PostAsync(url, content).Result;
response.EnsureSuccessStatusCode();
return response.Content.ReadAsAsync<MyClass>().Result;
}
However, I am experiencing a problem very similar to one described in this question, whereby everything works fine when the requests are routed via Fiddler, but it hangs after the 4th or 5th request when Fiddler is disabled.
If the cause of the problem is the same, I assume I need to do something more with HttpClient to get it to fully release its resources after each request but I am unable to find any code samples that show how to do this.
Hoping somebody can point me in the right direction.
Many thanks,
Tim
You are not disposing of the HttpResponseMessage object. This can leave open streams with the server, and after some quota of streams with an individual server is filled, no more requests will be sent.
using (var client = new HttpClient())
{
var content = new StringContent(data, Encoding.UTF8, "text/html");
using(var response = client.PostAsync(url, content).Result)
{
response.EnsureSuccessStatusCode();
return response.Content.ReadAsAsync<MyClass>().Result;
}
}

Adding authentication to security header in WCF to consume Metro WSIT service

I use this simple way to attach username and password to the SOAP request header. This works fine inside Java boundaries, but I want to be able to call it with my WCF client. How do I do this?
I've tried the following code, but it does not include the credentials in the header:
wsClient.ClientCredentials.UserName.UserName = "Hello";
wsClient.ClientCredentials.UserName.Password = "World";
Thanks in advance!
That is quite awful non-standardized way. It uses custom HTTP Headers so you cannot expect that built in WCF mechanism will magically support such approach. How should WCF know that you want to add custom non-standard HTTP header to HTTP request (not SOAP header)?
Use this:
var proxy = new YourServiceClient();
using (var scope = new OperationContextScope(proxy.InnerChannel))
{
var prop = new HttpRequestMessageProperty();
prop.Headers.Add("UserName", "Hello");
prop.Headers.Add("Password", "World");
OperationContext context = OperationContext.Current;
context.OutgoingMessageProperties[HttpRequestMessageProperty.Name] = prop;
proxy.CallYourOperation();
}