0

I use HttpClient to obtain access token, but I got error Method not allowed I tried from postman and I was able to get tokens successfully. But even though I use the PostAsync method of the HttpClient class, method GET appears in the response. Isn't that strange?

enter image description here

private async Task<string> GetTokenAsync(string username,string password)
        {
            string accessToken;
            var jsonInput = jsonSerializer.Serialize(new { email = username, password = password });
            var requestContent = new StringContent(jsonInput, Encoding.UTF8, "application/json");
            var response = await httpClient.PostAsync(@"api/user/token/obtain", requestContent);
            response.EnsureSuccessStatusCode();
            var content = await response.Content.ReadAsStringAsync();
            accessToken = jsonSerializer.Deserialize<IntegraAuth>(content).access;
            return accessToken;
        }
Adem Aygun
  • 550
  • 2
  • 6
  • 25
  • 1
    You can also attempt to setup the `HttpRequestMessage` object yourself, and set its `Method` property to `HttpMethod.Post`, and then send it out with `.SendAsync()`. This may be useful to help figure out the situation, before you try to figure out if your server is messed up like how @SupaMaggie70b mentioned – Narish Nov 28 '22 at 18:59
  • By chance, did you used to have `GetAsync` on that line and changed it? I wonder if you're debugging an older version. That *shouldn't* happen, but try Build menu -> Clean Solution and try again. – Gabriel Luci Nov 28 '22 at 19:09
  • @Narish I used `SendAsync` and set `Method=HttpMethod.Post` . but the result did not change. – Adem Aygun Nov 28 '22 at 19:12
  • @GabrielLuci I cleaned and rebuild but unfortunately it didn't work – Adem Aygun Nov 28 '22 at 19:20
  • 4
    just quessing: https://stackoverflow.com/questions/66358024/why-does-httpclient-postasync-appear-to-be-sending-the-request-as-a-get-rather-t maybe get-post confusion because somehow content empty; actually I would check header/content/request in postman, as better to start where it works – user13322060 Nov 28 '22 at 19:41
  • 1
    It may be the redirect issue described in that answer above (server responds with 301 and client automatically retries with GET). Is the URL in `response.RequestMessage` different than the URL you gave it? You can try disabling auto redirect with https://stackoverflow.com/a/10647245/1202807 – Gabriel Luci Nov 28 '22 at 20:08
  • 1
    @user13322060 I added slash end of the requestUri(not baseAddress) and it resolved. thank you – Adem Aygun Nov 28 '22 at 20:44

0 Answers0