0

There has been a lot of similar questioning on this one but I could not get any answers working for me..

I am calling another api Post request from my controller..but I get a 400 bad request all the time..

public async Task<JsonResult> TestSCIMPost(AppAuth auth)
{
    //Method 3:
    HttpClient client = new HttpClient();
        var jsonRequest = Newtonsoft.Json.JsonConvert.SerializeObject(auth);
        var content = new StringContent(jsonRequest);
        content.Headers.Remove("Content-Type");
        content.Headers.Add("Content-Type", "application/json");
        HttpResponseMessage response = await client.PostAsJsonAsync(
           URL, content);

        return new JsonResult(response);
}

curl curl -X POST "https://localhost:5001/api/Employee/api/Employee/TestSCIMPost" -H "accept: /" -H "Content-Type: application/json-patch+json" -d "{"client_id":"xyz","grant_type":"cc","client_secret":"abc","scope":"read"}"

enter image description here I have tried a couple of other ways that I am listing below..

public async Task<JsonResult> TestSCIMPost(AppAuth auth)
    {

        /*var response = string.Empty;
        var jsonRequest = Newtonsoft.Json.JsonConvert.SerializeObject(auth);
        byte[] messageBytes = System.Text.Encoding.UTF8.GetBytes(jsonRequest);
        var content = new ByteArrayContent(messageBytes);
        //HttpContent c = new StringContent(jsonRequest, Encoding.UTF8, "application/json");
        content.Headers.Remove("Content-Type");
        content.Headers.Add("Content-Type", "application/json");
        //content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json");
        using (var client = new HttpClient())
        {
            //client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
            HttpResponseMessage result = await client.PostAsync(URL, content);
            if (result.IsSuccessStatusCode)
            {
                response = result.StatusCode.ToString();
            }
        }*/
        //Method:2
        //HttpClient client = new HttpClient();
        //client.BaseAddress = new Uri(URL);
        //client.DefaultRequestHeaders.Accept.Clear();
        //client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("*/*"));

        //var requestMessage = Newtonsoft.Json.JsonConvert.SerializeObject(auth);
        //var content = new StringContent(requestMessage, Encoding.UTF8, "application/json");
        //content.Headers.Remove("Content-Type");
        //content.Headers.Add("Content-Type", "application/json");
        //HttpResponseMessage result = await client.PostAsync(URL, content);

        return new JsonResult(response);
    }

The body is coming from auth (frontend that i am serializing and adding in my request)

What's going wrong here? Is it utf-encoding? how to fix?

sideshowbarker
  • 81,827
  • 26
  • 193
  • 197
Samra
  • 1,815
  • 4
  • 35
  • 71
  • 1
    400 usually means that your method does not like the `Model` that is being passed to it. Did you try giving the `[FromBody]` attribute: `public async Task TestSCIMPost([FromBody]AppAuth auth)` – Rahul Sharma Feb 07 '22 at 06:45
  • The use of this code looks very wierd yte[] messageBytes = System.Text.Encoding.UTF8.GetBytes(jsonRequest); var content = new ByteArrayContent(messageBytes); can you also post a sample copy of thow the auth object is defined? – Tore Nestenius Feb 07 '22 at 09:02
  • Try it again with StringContent and content type of application/json-patch+json. You could also use NSwag to generate an http client for you based on that swagger endpoint. In the future please provide a minimal reproducible example without all the comment clutter. – Crowcoder Feb 07 '22 at 12:38

1 Answers1

0

One reason this can happen is if you are posting content in the body (as you are doing) where the parser expects to find it in the query.

So if you have something like this:

string url = "https://localhost:5001/api/Employee/TestSCIMPost";
var content = new StringContent("{\"client_id\":\"xyz\",\"grant_type\":\"cc\"}");
HttpResponseMessage response = await client.PostAsync(url, content);

Try changing it to this:

string url = "https://localhost:5001/api/Employee/TestSCIMPost?client_id=xyz&grant_type=cc";
var content = new StringContent("");
HttpResponseMessage response = await client.PostAsync(url, content);
Tawab Wakil
  • 1,737
  • 18
  • 33
  • Thank you Tawab; Your answer helped me cross half the problem. I am no more getting 400 error. But only thing is content, response.content both are empty; API server responds with 200 Ok. But while checking in the postman, i get proper response. any comments ? My code looks like below with httpClient.BaseAddress already set
    var content = new StringContent(""); HttpResponseMessage response = await httpClient.PostAsync($"userLogin?userName={userName}&userPassword={userPassword}", content);
    – Srikanth S Oct 06 '22 at 15:13
  • Your code there looks fine, so I'm not sure. This is a different issue that may warrant posting a new question that includes your controller class and HTTP client instantiation as the problem may be in one of those areas. – Tawab Wakil Oct 06 '22 at 17:37
  • Hi, I have posted a new question here https://stackoverflow.com/questions/73981134/postasync-returns-status-as-200-ok-but-response-content-is-empty-while-data-is – Srikanth S Oct 07 '22 at 00:30