liamrhomer
liamrhomer

Reputation: 1

Why is HttpClient.PostAsync call to a Startsharp Serenity platform returning Code: 400?

I am developing this in Visual Studio 2022 using Xamarin framework.

I am trying to obtain the necessary authorization cookie (.AspNetAuth) from a StartSharp Serenity application so that I can utilize and call the endpoints through a mobile app I am developing for our engineers to use while offline on site.

To get the cookie I require, I am using the HttpClient.PostAsync functionality but this is always returning a 400 response even though the headers and body I am using match an identical call I have tested in Insomnia.

I have the following code which is returning a response code of 400 - the code utilizes a number of httpClient.GetAsync functions to collect the cookies required for the Post and these all work fine (e.g. GET_AntiForgeryCookie(csfrUrl)):

public async Task POST_ASPNetAuthCookie(Uri loginUrl, Uri csfrUrl)
{
    var cookies = new CookieContainer();
    cookies.Add(await GET_AntiForgeryCookie(csfrUrl));
    cookies.Add(await GET_CSFRCookie2(csfrUrl));

    var handler = new HttpClientHandler
    {
        CookieContainer = cookies,
    };

    var httpClient = new HttpClient(handler, true);
    ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
    httpClient.DefaultRequestHeaders.Add("Accept", "*/*");

    httpClient.DefaultRequestHeaders.Add("User-Agent", "VisStu2022");
    httpClient.DefaultRequestHeaders.Add("X-CSRF-TOKEN", await GET_CSFRCookie(csfrUrl));

    string json = "{\r\t\"Username\": \"user\",\r\t\"Password\": \"pass\"\r}";
    byte[] messageBytes = Encoding.UTF8.GetBytes(json);
    var content = new ByteArrayContent(messageBytes); 

    content.Headers.ContentType = new MediaTypeHeaderValue("application/json");

    var response = await httpClient.PostAsync(loginUrl, content);
    var responseString = response.IsSuccessStatusCode;
    var cookie = cookies.GetCookies(loginUrl).Cast<Cookie>().FirstOrDefault(x => x.Name == ".AspNetAuth");
}

I have configured an Insomnia call with the same headers, cookies and body and checked them both through Fiddler where they look identical (apart from the order of the headers), however the Insomnia call is coming back as a 200 success and the Visual Studio Xamarin call is coming back as 400.

I have tried this through the VS Android emulator (Pixel 5 - API 33) and a real android device (Nexus 7) and both have returned the same response. I do not have access to an iPhone to check that at this point.

Does anyone have any idea what might be going wrong?

Upvotes: 0

Views: 82

Answers (0)

Related Questions