ronconsoda
ronconsoda

Reputation: 117

Is there a way to pass this contenttype "application/x-www-form-urlencoded;v=2.0" in C#?

I am trying to replicate in C# the following code in CURL. Note that this code is working correctly with curl. I am using this https://curl.olsh.me/ to create the request.

curl -k -u "Default User:robotics" -H "Content-Type: application/x-www-form-urlencoded;v=2.0" -d "value=TRUE" "https://localhost/rw/rapid/symbol/RAPID/T_ROB1/EGMDemo/run_egm/data?mastership=implicit"

I have tried to translate this command to c# and when arriving to the line:

request.Content.Headers.ContentType = new MediaTypeHeaderValue("application/x-www-form-urlencoded;v=2.0");

I receive an exception that application/x-www-form-urlencoded;v=2.0 is not valid. How can I pass this content type? If it is not possible with httpclient is there any other way to do it?


    var handler = new HttpClientHandler();
    handler.ServerCertificateCustomValidationCallback = (requestMessage, certificate, chain, policyErrors) => true; 

    using (var httpClient = new HttpClient(handler))
    {
        using (var request = new HttpRequestMessage(new HttpMethod("POST"), "https://localhost/rw/rapid/symbol/RAPID/T_ROB1/EGMDemo/run_egm/data?mastership=implicit"))
        {
            var base64authorization = Convert.ToBase64String(Encoding.ASCII.GetBytes("Default User:robotics"));
            request.Headers.TryAddWithoutValidation("Authorization", $"Basic {base64authorization}"); 

            request.Content = new StringContent("value=TRUE");
            request.Content.Headers.ContentType = new MediaTypeHeaderValue("application/x-www-form-urlencoded;v=2.0"); 

            var response = await httpClient.SendAsync(request);
        }
    }


Upvotes: 0

Views: 435

Answers (1)

fhayd
fhayd

Reputation: 23

You can try to directly use request.Content.Headers.Add("Content-Type", "application/x-www-form-urlencoded;v=2.0");

MediaTypeHeaderValue provide support only for standard media type as defined for HTTP/1.1

EDIT mistake :)

Upvotes: 1

Related Questions