Link to home
Start Free TrialLog in
Avatar of Philippe Renaud
Philippe RenaudFlag for Canada

asked on

Unable to PostAsync for api Error 400 ?

Hello EE,


I am able to POST Api with Swagger UI, but when it comes to really try it with my iOS Xamarin solution in vs2022, it does not work, having an error 404 bad request.


The funny thing is, if I copy paste the JSON (with a break point) and i try it in swagger ui, it does work! so Im confused.


the Task to PostAsync looks like this :


public static async Task AddProfession(int customerID, string firstname, string lastname, string emplacement)
        {             var imageTmp = "test.jpg";             var profession = new Profession             {                 CustomerID = customerID,                 Firstname = firstname,                 Lastname = lastname,                 Fullname = firstname + " " + lastname,                 Emplacement = emplacement,                 Image = imageTmp,                 Rating = 0             };                 var json = JsonConvert.SerializeObject(profession);             var content = new StringContent(json, Encoding.UTF8, "application/json");             var response = await client.PostAsync("api/Professions", content);             if (!response.IsSuccessStatusCode)             {             }         }

Open in new window


Anoyone knows whats going on ?


Avatar of Jonathan D.
Jonathan D.
Flag of Israel image

Try setting a breakpoint on var content =  and look what json is being generated. If there's a difference between your hard coded json then you should know there's a problem how the model is being serialized. If can, please post the back end code that processes this request.
Avatar of Philippe Renaud

ASKER

OK, I did it :

the breakpoint on content, will show the JSON (thats the Text Visualizer) :

User generated imagefyi: the ID in SQL table is auto-identity YES and DateAddedhas a default value getdate()

I actually copied paste this exactly in swagger ui and it worked.
But I see this in response in my VS2022:  {StatusCode: 400, ReasonPhrase: 'Bad Request', Version: 1.1,

ApplicationInsights in azure doest help much on this error.
Very confusing..I just cannot understand it.
Please paste here the code snippet of the back end api that processes this request.
here it is, (it was created by Scaffolding)

     // POST: api/Professions
        // To protect from overposting attacks, see https://go.microsoft.com/fwlink/?linkid=2123754
        [HttpPost]
        public async Task<ActionResult<Profession>> PostProfession(Profession profession)
        {
            _context.Professions.Add(profession);
            await _context.SaveChangesAsync();

            return CreatedAtAction("GetProfession", new { id = profession.Id }, profession);
        }

Open in new window

You should perform data validation in your back end api before trying to add to EF a data model and saving changes to the database, it's like you're positive you're going to get a Profession model (who guarantees that?) without validating the incoming data from the request. Despite that, I don't see anywhere in the back end api you're doing some validation logic to return 400 bad request when there's a failure.

What I would do in this scenario is capture the request sent from your C# code to the api using an http sniffer like Fiddler and inspect the structure of the request compared to the manual one you're sending.

Please post here the result of the captured request from Fiddler so we can compare it to the one you're sending manually.
not sure why i dont see anything in fiddler when the Post happen in vs2022 ...
a guy told me : "Are you doing it over http or https? If it is just http then you need to do network config setup to allow clear text "

not sure how do I check this ? can you guys guide me ?
Avatar of louisfr
louisfr

var response = await client.PostAsync("api/Professions", content);

Open in new window

Is this the code you're actually using, or did you just hide part of the URL to post here?
Yes This is what im using, but client is another variable :

        static string BaseUrl = "https://xxxxxxxx.azurewebsites.net";
        static HttpClient client;

        static MyInternetService()
        {
            try
            {
                client = new HttpClient
                {
                    BaseAddress = new Uri(BaseUrl)
                };
            }
            catch
            {

            }
        }

Open in new window

Since the traffic goes through a secure connection, in order for Fiddler to see it you'd have to enable "SSL decryption" in options.
If i check  response.Content.ReadAsStringAsync().Result;    i see :

{"errors":{"":["A non-empty request body is required."]},"type":"https://tools.ietf.org/html/rfc7231#section-6.5.1","title":"One or more validation errors occurred.","status":400,"traceId":"00-0172d208061abfeb97fb43cd8ec51284-8ee2660150acdeed-00"}

do you know what: A non-empty request body is required. means?

do you know what: A non-empty request body is required. means?

It means that the body of the request you're sending is empty, in simple it means you're not sending the json included in the body of the request.

I have a feeling this has something to do with this lines:

var json = JsonConvert.SerializeObject(profession);
var content = new StringContent(json, Encoding.UTF8, "application/json"

Open in new window


You're serializing the model into json flat format, but it's not being set into the body. I'm not sure what StringContent is all about because I have never used it (nor HttpClient, I usually use WebClient) when making post requests, but I have a feeling that the json value goes somewhere else and not in the body.
In the azure logs, i see this message :

2022-02-25 13:58:06.939 +00:00 [DBG] The request has model state errors, returning an error response.


the post works in swagger, it works in postman.. but NOT in my damn iOs application
what am I supposed to do to know exactly the problem ?



ASKER CERTIFIED SOLUTION
Avatar of Philippe Renaud
Philippe Renaud
Flag of Canada image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial

Updating VS and iOS isn't a solution without knowing why it went back to work behind the scenes, but it's good to acknowledge your problem has been solved. Great job.


Edit: This was probably a bug in either VS or iOS, or both.