Search code examples
c#ajaxposthttpwebrequest

C# HttpWebRequest send xhr request - 400 bad request


I have to send ajax request from C#. In browser the request looks like:

Request URL:https://sts-service.mycompany.com/UPNFromUserName
Request method:POST
Remote address:xxxx
Status code:
200
Version:HTTP/2.0
Referrer Policy:strict-origin-when-cross-origin

Headers:

 Host: sts-service.mycompany.com
 User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:68.0) Gecko/20100101 Firefox/68.0
 Accept: */*
 Accept-Language: en-US,en;q=0.5
 Accept-Encoding: gzip, deflate, br
 Referer: https://sts.mycompany.com/
 Content-type: application/x-www-form-urlencoded
 Content-Length: 17
 Origin: https://sts.mycompany.com
 DNT: 1
 Connection: keep-alive
 Pragma: no-cache
 Cache-Control: no-cache

Params: Form data:

 MS.Aution

Cookies: no cookie

And in C# my request:

WebRequest webRequest = WebRequest.Create("https://sts-service.mycompany.com/UPNFromUserName");

((HttpWebRequest)webRequest).Referer = "https://sts.mycompany.com/";
((HttpWebRequest)webRequest).Host = "sts-service.mycompany.com";
((HttpWebRequest)webRequest).KeepAlive = true;
((HttpWebRequest)webRequest).AllowAutoRedirect = true;
((HttpWebRequest)webRequest).UseDefaultCredentials = true;
((HttpWebRequest)webRequest).UserAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:68.0) Gecko/20100101 Firefox/68.0";
webRequest.ContentType = "application/x-www-form-urlencoded";
((HttpWebRequest)webRequest).Accept = "*/*";

((HttpWebRequest)webRequest).Headers.Add("Origin", "https://sts.mycompany.com");
((HttpWebRequest)webRequest).Headers.Add("Accept-Encoding", "gzip, deflate, br");
((HttpWebRequest)webRequest).Headers.Add("Accept-Language", "en-US,en;q=0.5");
((HttpWebRequest)webRequest).Headers.Add("Upgrade-Insecure-Requests", @"1");
((HttpWebRequest)webRequest).Headers.Add("DNT", @"1");
((HttpWebRequest)webRequest).AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;
webRequest.Method = HttpRequestType.POST.ToString();
string msg = "MSCnE.Automation";

webRequest.ContentLength = msg.Length;
Stream reqStream = webRequest.GetRequestStream();
byte[] msgb = System.Text.Encoding.UTF8.GetBytes(msg);
reqStream.Write(msgb, 0, msgb.Length);
reqStream.Close();
var response = (HttpWebResponse)webRequest.GetResponse();

StreamReader sr = new StreamReader(response.GetResponseStream());
string Result = sr.ReadToEnd();
response.Close();

I get error:

The remote server returned an error: (400) Bad Request.

In browser in Network tab the request looks like: enter image description here

Type is json but in Headers Content Type is application/x-www-form-urlencoded Maybe this is the reason?


Solution

  • something along these lines (not tested):

        public async Task<string> SendPOST()
                {
                    var dict = new Dictionary<string, string>();
                    dict.Add("DNT", "1");
                    dict.Add("someformdata","MSCnE.Automation");
                    using (var formdata = new System.Net.Http.FormUrlEncodedContent(dict))
                    {
                        //do not use using HttpClient() - https://learn.microsoft.com/en-us/dotnet/api/system.net.http.httpclient
                        using (System.Net.Http.HttpClient httpClient = new System.Net.Http.HttpClient())    
                        {
                            formdata.Headers.ContentType = System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/x-www-form-urlencoded");
                            formdata.Headers.ContentType.CharSet = "UTF-8";
                            httpClient.DefaultRequestHeaders.Add("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:68.0) Gecko/20100101 Firefox/68.0");
                            using (var response = await httpClient.PostAsync("https://sts-service.mycompany.com/UPNFromUserName", formdata))
                            {
                                if (response.IsSuccessStatusCode)
                                {
                                    var postresult = await response.Content.ReadAsStringAsync();
                                    return postresult;
                                }
                                else
                                {
                                    string errorresult = await response.Content.ReadAsStringAsync();
                                    return errorresult;
                                }
                            }
                        }
                    }
                }