You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
Cannot Send GET Request with Content-Type Header with RestSharp v107 #1722
After upgrading to v107, I started getting the following error when trying to execute a GET request with the Content-Type: application/force-download header: Cannot send a content-body with this verb-type.
The header is the only parameter in the request, but it seems like RestSharp transparently adds a body causing the error.
All attempts below causes the error mentioned when executing the request: restRequest.AddHeader("Content-Type", "application/force-download"); restRequest.Parameters.AddParameter(new BodyParameter("", "", "application/force-download", DataFormat.None)); restRequest.AddStringBody("", "application/force-download");
While it may not be a good practice to use this header parameter with a GET request, it is unfortunately required for me to perform some operation with a system from a vendor and the last version of RestSharp does not support this anymore.
Hm, right now the content-type header is added to the content, and if there's no content, there's no header set. There was an issue about it here and I implemented the proposed change to add an empty body.
It is not RestSharp that fails the request, it's the particular implementation of HttpClient. I bet you are on .NET < 5?
I don't know how long it can take for this issue to be closed so I built a .NET 6 project that includes a class that uses RestSharp v107 to try and resolve my issue.
However, a .NET project cannot be referenced from a .NET Framework one.
I believe a .NET Standard (and maybe a .NET Core) project can be referenced by a .NET Framework one, but I'm not sure if switching to .NET Standard 2.1 or .NET Core 3.1 would fix my issue with RestSharp.
What do you suggest me to do?
Give you more time (if so, would it be possible to get an ETA?)
.NET Standard is just an API surface, it doesn't have any implementation. It will use the underlying SDK API, so if you reference a .NET Standard package in .NET 4.8 project, it will use .NET 4.8.
Basically, it's not an exception produced by RestSharp, it's what HttpClient does, so if you use HttpClient directly, you will get the same issue. The workaround using a delegating handler is equally applicable for RestSharp as you can supply a delegating handler in client options.
Btw RestSharp for .NET Standard doesn't include any reference to System.Net.Http, which you'd need to add yourself. I tested it with 4.3.4 and it worked, maybe it's an easy fix for you actually to update the package version.
I added a test for it targeting .NET Framework 4.8 and it passes on my machine (macOS) but fails in the CI pipeline (Windows). So, it's not only framework-specific, it is also platform-specific.
I tried to add the Content-Type header to the request itself and got this:
System.InvalidOperationException
Misused header name. Make sure request headers are used with HttpRequestMessage, response headers with HttpResponseMessage, and content headers with HttpContent objects.
Honestly, I don't think it's possible with HttpClient. If you know how to avoid these exceptions, please add a comment here.
Tried with .NET 6 and .NET Framework 4.8 and both worked. Could you create a repro repository and share it here?
I have error with "content-type", "application/x-www-form-urlencoded"
old source code
var client = new RestClient("urSite") {
Timeout = -1,
Proxy = clientProxy
};
var request = new RestRequest(Method.POST);
request.AddHeader("accept", "application/json");
request.AddHeader("accept-language", "en-US,en;q=0.9");
request.AddHeader("content-type", "application/x-www-form-urlencoded");
request.AddHeader("origin", "url");
request.AddHeader("referer", "ur;");
client.UserAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.110 Safari/537.36";
request.AddParameter("application/x-www-form-urlencoded",$"body",ParameterType.RequestBody);
var response = await client.ExecuteAsync(request);
and this is new version
var options = new RestClientOptions(token.Url) {
Proxy = proxy,
UserAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.110 Safari/537.36"
};
var request = new RestClient(options);
var postPayload = new RestRequest {
Method = Method.Post,
};
postPayload.AddHeader("accept", "application/json");
postPayload.AddHeader("accept-language", "en-US,en;q=0.9");
postPayload.AddHeader("content-type", "application/x-www-form-urlencoded");
postPayload.AddHeader("origin", "urlorigin");
postPayload.AddHeader("referer", "urlReferer");
postPayload.AddParameter("application/x-www-form-urlencoded", token.PostPayload, ParameterType.RequestBody);
var response = await request.ExecuteAsync(postPayload);
and receive error
`'Misused header name, 'content-type'. Make sure request headers are used with HttpRequestMessage, response headers with HttpResponseMessage, and content headers with HttpContent objects.'`
I using net core 6 web api in windows
I managed to apply a fix with a utility class using System.Net.HttpClient directly.
The implementation might be too dirty for many, but the usage is very simple and clean:
// using System.Net.Http;// using System.Net.Http.Headers;// using System.Linq;// using System.Threading;// using System.Threading.Tasks;// using System.Collections.Generic;// using System.Reflection;// using RestSharp;publicstaticclassHttpMessageUtils{publicconststringContentTypeHeaderName="Content-Type";classHandlerAllowingContentTypeHeaderOnGetRequests:DelegatingHandler{publicHandlerAllowingContentTypeHeaderOnGetRequests(HttpMessageHandlerp_innerHttpMessageHandler):base(p_innerHttpMessageHandler){}protectedoverrideasyncTask<HttpResponseMessage>SendAsync(HttpRequestMessagep_request,CancellationTokenp_cancellationToken){FieldInfoinvalidHeadersField=typeof(HttpHeaders).GetField("invalidHeaders",BindingFlags.NonPublic|BindingFlags.Instance)??// System.Net.Http v2.2+typeof(HttpHeaders).GetField("_invalidHeaders",BindingFlags.NonPublic|BindingFlags.Instance)// System.Net.Http before v2.2;HashSet<string>invalidHeaders=(HashSet<string>)invalidHeadersField.GetValue(p_request.Headers);if(invalidHeaders.Contains(ContentTypeHeaderName)){invalidHeaders.Remove(ContentTypeHeaderName);stringcontentTypeHeaderValue=p_request.Content.Headers.ContentType.MediaType;stringrequestContent=awaitp_request.Content.ReadAsStringAsync();if(string.IsNullOrWhiteSpace(requestContent))p_request.Content=null;elsep_request.Content.Headers.Remove(ContentTypeHeaderName);p_request.Headers.Add(ContentTypeHeaderName,contentTypeHeaderValue);}HttpResponseMessageresponse=awaitbase.SendAsync(p_request,p_cancellationToken);returnresponse;}}publicstaticHttpClientGetHttpClient(thisRestClientp_restClient){return((TypeInfo)p_restClient.GetType()).DeclaredProperties.First(p =>p.Name=="HttpClient").GetValue(p_restClient)asHttpClient;}privatestaticFieldInfoGetHttpMessageHandlerField(thisHttpClientp_httpClient){return((TypeInfo)p_httpClient.GetType().BaseType).DeclaredFields.First(f =>f.Name=="handler");}publicstaticHttpMessageHandlerGetMessageHandler(thisHttpClientp_httpClient){returnp_httpClient.GetHttpMessageHandlerField().GetValue(p_httpClient)asHttpMessageHandler;}publicstaticvoidSetMessageHandler(thisHttpClientp_httpClient,HttpMessageHandlerp_newHttpMessageHandler){p_httpClient.GetHttpMessageHandlerField().SetValue(p_httpClient,p_newHttpMessageHandler);}publicstaticHttpMessageHandlerGetInnerMessageHandler(thisRestClientp_restClient){returnp_restClient.GetHttpClient().GetMessageHandler();}publicstaticvoidAllowContentTypeHeaderOnGetRequests(thisRestClientp_restClient){HttpMessageHandlerinnerMessageHandler=p_restClient.GetInnerMessageHandler();HttpMessageHandlernewMessageHandler=newHandlerAllowingContentTypeHeaderOnGetRequests(innerMessageHandler);p_restClient.GetHttpClient().SetMessageHandler(newMessageHandler);}}
@PierreCollardSuero I saw a similar approach with a delegating handler replacing the content type by hand. As you rightfully mentioned, it looks like a heavy hack. You indeed can configure the delegating handler. You can make it even easier by using RestClientOptions.ConfigureMessageHandler
@VictorRH I wrote in the docs that you should not set the content type header manually. Please read the docs.
in my case is necessary send headers , and i have similar error with content-length and request.AddStringBody(jsonString, ContentType.Json); not working with content-lenght, because this not have any ContentType, my end point require headers
@VictorRH have you read the docs following the link I posted? RestSharp adds the necessary headers automatically if the request has a body.
Here's the code that would work:
varoptions=newRestClientOptions("https://enqvvdg27q3o.x.pipedream.net/"){UserAgent="Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.110 Safari/537.36"};varpayload="key=value&foo=bar";varclient=newRestClient(options);varrequest=newRestRequest("",Method.Post).AddHeader("Accept-Language","en-US,en;q=0.9").AddHeader("Origin","urlorigin").AddHeader("Referer","urlReferer").AddStringBody(payload,"application/x-www-form-urlencoded");varresponse=awaitclient.ExecutePostAsync(request);
and here is what the request looks like:
Notice that the content-type header is present, although if you use HttpTracer you won't see it. It's because HttpTracer does not print out content headers, it only shows you request headers.
@PierreCollardSuero I saw a similar approach with a delegating handler replacing the content type by hand. As you rightfully mentioned, it looks like a heavy hack. You indeed can configure the delegating handler. You can make it even easier by using RestClientOptions.ConfigureMessageHandler
Thanks @alexeyzimarev, the StackOverflow link you had provided guided me toward the solution I implemented.
I had first tried with RestClientOptions.ConfigureMessageHandler and it didn't work for me as the handler wasn't being called.
Most likely, I missed something, but I am satisfied with the solution I provided.
At least, the utility class can be isolated in its own file and I only have to add one line where I make the request.
So you can close the issue whenever you feel it is appropriate.
Thanks for the help!
Strange that ConfigureMessageHandler didn't work for you, as I use it in some tests and it works. I copied the code from the test to the docs: https://restsharp.dev/v107/#delegating-handlers
Activity
alexeyzimarev commentedon Jan 25, 2022
Hm, right now the content-type header is added to the content, and if there's no content, there's no header set. There was an issue about it here and I implemented the proposed change to add an empty body.
It is not RestSharp that fails the request, it's the particular implementation of
HttpClient. I bet you are on .NET < 5?PierreCollardSuero commentedon Jan 25, 2022
Yes, I am using .NET Framework 4.8. Is there a way to work with
HttpClientto implement a workaround instead of upgrading the .NET version?alexeyzimarev commentedon Jan 26, 2022
I saw a question on SO about setting the content type header, it looks like it can be set on the request itself. I will look into it.
PierreCollardSuero commentedon Feb 2, 2022
Microsoft recommends to extend a .NET Framework application with a .NET one rather than migrating it entirely to .NET which makes sense as it would be a lot of work:
https://docs.microsoft.com/en-us/dotnet/standard/choosing-core-framework-server
I don't know how long it can take for this issue to be closed so I built a .NET 6 project that includes a class that uses RestSharp v107 to try and resolve my issue.
However, a .NET project cannot be referenced from a .NET Framework one.
I believe a .NET Standard (and maybe a .NET Core) project can be referenced by a .NET Framework one, but I'm not sure if switching to .NET Standard 2.1 or .NET Core 3.1 would fix my issue with RestSharp.
What do you suggest me to do?
alexeyzimarev commentedon Feb 2, 2022
.NET Standard is just an API surface, it doesn't have any implementation. It will use the underlying SDK API, so if you reference a .NET Standard package in .NET 4.8 project, it will use .NET 4.8.
alexeyzimarev commentedon Feb 2, 2022
Check this one: https://stackoverflow.com/questions/26109650/explicitly-set-content-type-headers-for-get-operation-in-httpclient
Basically, it's not an exception produced by RestSharp, it's what HttpClient does, so if you use HttpClient directly, you will get the same issue. The workaround using a delegating handler is equally applicable for RestSharp as you can supply a delegating handler in client options.
alexeyzimarev commentedon Feb 2, 2022
I made this code:
Tried with .NET 6 and .NET Framework 4.8 and both worked. Could you create a repro repository and share it here?
alexeyzimarev commentedon Feb 2, 2022
That's how the request looks like:

#1725 set the timeout status correctly
alexeyzimarev commentedon Feb 2, 2022
Btw RestSharp for .NET Standard doesn't include any reference to
System.Net.Http, which you'd need to add yourself. I tested it with 4.3.4 and it worked, maybe it's an easy fix for you actually to update the package version.alexeyzimarev commentedon Feb 3, 2022
I added a test for it targeting .NET Framework 4.8 and it passes on my machine (macOS) but fails in the CI pipeline (Windows). So, it's not only framework-specific, it is also platform-specific.
I tried to add the
Content-Typeheader to the request itself and got this:Honestly, I don't think it's possible with
HttpClient. If you know how to avoid these exceptions, please add a comment here.VictorRH commentedon Feb 3, 2022
I have error with
"content-type", "application/x-www-form-urlencoded"old source code
and this is new version
PierreCollardSuero commentedon Feb 3, 2022
I managed to apply a fix with a utility class using
System.Net.HttpClientdirectly.The implementation might be too dirty for many, but the usage is very simple and clean:
alexeyzimarev commentedon Feb 3, 2022
@VictorRH I wrote in the docs that you should not set the content type header manually. Please read the docs.
alexeyzimarev commentedon Feb 3, 2022
@PierreCollardSuero I saw a similar approach with a delegating handler replacing the content type by hand. As you rightfully mentioned, it looks like a heavy hack. You indeed can configure the delegating handler. You can make it even easier by using
RestClientOptions.ConfigureMessageHandlerVictorRH commentedon Feb 3, 2022
in my case is necessary send headers , and i have similar error
with content-lengthandrequest.AddStringBody(jsonString, ContentType.Json);not working withcontent-lenght, because this not have anyContentType, my end point require headersalexeyzimarev commentedon Feb 4, 2022
@VictorRH have you read the docs following the link I posted? RestSharp adds the necessary headers automatically if the request has a body.
Here's the code that would work:
and here is what the request looks like:
Notice that the content-type header is present, although if you use HttpTracer you won't see it. It's because HttpTracer does not print out content headers, it only shows you request headers.
PierreCollardSuero commentedon Feb 4, 2022
Thanks @alexeyzimarev, the StackOverflow link you had provided guided me toward the solution I implemented.
I had first tried with
RestClientOptions.ConfigureMessageHandlerand it didn't work for me as the handler wasn't being called.Most likely, I missed something, but I am satisfied with the solution I provided.
At least, the utility class can be isolated in its own file and I only have to add one line where I make the request.
So you can close the issue whenever you feel it is appropriate.
Thanks for the help!
alexeyzimarev commentedon Feb 5, 2022
Strange that
ConfigureMessageHandlerdidn't work for you, as I use it in some tests and it works. I copied the code from the test to the docs: https://restsharp.dev/v107/#delegating-handlers