Skip to content

Cannot Send GET Request with Content-Type Header with RestSharp v107 #1722

Closed

Description

@PierreCollardSuero

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.

Activity

  1. alexeyzimarev commented on Jan 25, 2022

    @alexeyzimarev
    Member

    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?

  2. PierreCollardSuero commented on Jan 25, 2022

    @PierreCollardSuero
    Author

    Yes, I am using .NET Framework 4.8. Is there a way to work with HttpClient to implement a workaround instead of upgrading the .NET version?

  3. alexeyzimarev commented on Jan 26, 2022

    @alexeyzimarev
    Member

    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.

  4. PierreCollardSuero commented on Feb 2, 2022

    @PierreCollardSuero
    Author

    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?

    • Give you more time (if so, would it be possible to get an ETA?)
    • Build a .NET Standard/Core library
    • Revert to RestSharp v106
    • etc.
  5. alexeyzimarev commented on Feb 2, 2022

    @alexeyzimarev
    Member

    .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.

  6. alexeyzimarev commented on Feb 2, 2022

    @alexeyzimarev
    Member

    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.

  7. alexeyzimarev commented on Feb 2, 2022

    @alexeyzimarev
    Member

    I made this code:

            var options = new RestClientOptions("https://enlgqo6062j5.x.pipedream.net/");
            var client  = new RestClient(options);
    
            var request = new RestRequest("resource");
            request.AddHeader("Content-Type", "application/force-download");
            var response = await client.GetAsync(request);

    Tried with .NET 6 and .NET Framework 4.8 and both worked. Could you create a repro repository and share it here?

  8. alexeyzimarev commented on Feb 2, 2022

    @alexeyzimarev
    Member

    That's how the request looks like:
    image

  9. added
    awaiting-info
    on Feb 2, 2022
  10. added a commit that references this issue on Feb 2, 2022
  11. alexeyzimarev commented on Feb 2, 2022

    @alexeyzimarev
    Member

    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.

  12. alexeyzimarev commented on Feb 3, 2022

    @alexeyzimarev
    Member

    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.

  13. VictorRH commented on Feb 3, 2022

    @VictorRH

    I made this code:

            var options = new RestClientOptions("https://enlgqo6062j5.x.pipedream.net/");
            var client  = new RestClient(options);
    
            var request = new RestRequest("resource");
            request.AddHeader("Content-Type", "application/force-download");
            var response = await client.GetAsync(request);

    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
    
  14. PierreCollardSuero commented on Feb 3, 2022

    @PierreCollardSuero
    Author

    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;
    
    public static class HttpMessageUtils
    {
        public const string ContentTypeHeaderName = "Content-Type";
    
        class HandlerAllowingContentTypeHeaderOnGetRequests : DelegatingHandler
        {
            public HandlerAllowingContentTypeHeaderOnGetRequests(
                HttpMessageHandler p_innerHttpMessageHandler
            ) : base(p_innerHttpMessageHandler)
            { }
    
            protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage p_request, CancellationToken p_cancellationToken)
            {
                FieldInfo invalidHeadersField =
                    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);
    
                    string contentTypeHeaderValue = p_request.Content.Headers.ContentType.MediaType;
                    string requestContent = await p_request.Content.ReadAsStringAsync();
    
                    if (string.IsNullOrWhiteSpace(requestContent))
                        p_request.Content = null;
                    else
                        p_request.Content.Headers.Remove(ContentTypeHeaderName);
    
                    p_request.Headers.Add(ContentTypeHeaderName, contentTypeHeaderValue);
                }
    
                HttpResponseMessage response = await base.SendAsync(p_request, p_cancellationToken);
                return response;
            }
        }
    
        public static HttpClient GetHttpClient(this RestClient p_restClient)
        {
            return ((TypeInfo)p_restClient.GetType())
                .DeclaredProperties
                .First(p => p.Name == "HttpClient")
                .GetValue(p_restClient)
                as HttpClient
            ;
        }
    
        private static FieldInfo GetHttpMessageHandlerField(this HttpClient p_httpClient)
        {
            return ((TypeInfo)p_httpClient.GetType().BaseType)
                .DeclaredFields
                .First(f => f.Name == "handler")
            ;
        }
    
        public static HttpMessageHandler GetMessageHandler(this HttpClient p_httpClient)
        {
            return p_httpClient.GetHttpMessageHandlerField()
                .GetValue(p_httpClient)
                as HttpMessageHandler
            ;
        }
    
        public static void SetMessageHandler(this HttpClient p_httpClient, HttpMessageHandler p_newHttpMessageHandler)
        {
            p_httpClient.GetHttpMessageHandlerField().SetValue(p_httpClient, p_newHttpMessageHandler);
        }
    
        public static HttpMessageHandler GetInnerMessageHandler(this RestClient p_restClient)
        {
            return p_restClient.GetHttpClient().GetMessageHandler();
        }
    
        public static void AllowContentTypeHeaderOnGetRequests(this RestClient p_restClient)
        {
            HttpMessageHandler innerMessageHandler = p_restClient.GetInnerMessageHandler();
            HttpMessageHandler newMessageHandler = new HandlerAllowingContentTypeHeaderOnGetRequests(innerMessageHandler);
            p_restClient.GetHttpClient().SetMessageHandler(newMessageHandler);
        }
    }
    RestClientOptions restClientOptions = new(p_baseURL) { Credentials = p_credentials };
    RestClient restClient = new(restClientOptions);
    RestRequest restRequest = new(p_relativeResourcePath, p_method);
    
    restRequest.AddHeader("Content-Type", "application/force-download");
    restClient.AllowContentTypeHeaderOnGetRequests();
    RestResponse restResponse = await restClient.ExecuteAsync(restRequest, p_method);
  15. alexeyzimarev commented on Feb 3, 2022

    @alexeyzimarev
    Member

    @VictorRH I wrote in the docs that you should not set the content type header manually. Please read the docs.

  16. alexeyzimarev commented on Feb 3, 2022

    @alexeyzimarev
    Member

    @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

  17. VictorRH commented on Feb 3, 2022

    @VictorRH

    @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

  18. alexeyzimarev commented on Feb 4, 2022

    @alexeyzimarev
    Member

    @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:

    var options = new RestClientOptions("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"
    };
    var payload = "key=value&foo=bar";
    var client = new RestClient(options);
    var request = new RestRequest("", Method.Post)
        .AddHeader("Accept-Language", "en-US,en;q=0.9")
        .AddHeader("Origin", "urlorigin")
        .AddHeader("Referer", "urlReferer")
        .AddStringBody(payload, "application/x-www-form-urlencoded");
    
    var response = await client.ExecutePostAsync(request);

    and here is what the request looks like:

    image

    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.

  19. PierreCollardSuero commented on Feb 4, 2022

    @PierreCollardSuero
    Author

    @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!

  20. alexeyzimarev commented on Feb 5, 2022

    @alexeyzimarev
    Member

    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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    awaiting-info

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions