lundi 26 juillet 2021

Web Api POST - Param always null when called from Angular 11

This wasn't always the case, but came in today and cannot login to one of our sites. The backend is Web Api 2 and the front end is Angular 11. I've spent most of the day investigating the issue and these are my findings

  • It's possible to call the API from Postman without issue
  • Debugging the front end and API locally through IIS Express works without issue
  • Running the front end locally pointing to the server API endpoint does not work
  • Using the front end and back end on the server does not work

The issue appears to be that when calling from Angular to the API hosted in IIS the serialiser does not populate the model and it remains null.

        [HttpPost]
        public IHttpActionResult PostUserToken(LoginDetails ld)
        {
            //ld is null here

            if (CheckUser(...)
            {
                return Ok(...);
            }

            return Unauthorized();
        } 

However if I modify it to

        [HttpPost]
        public IHttpActionResult PostUserToken()
        {
            string str = new System.IO.StreamReader(HttpContext.Current.Request.InputStream).ReadToEnd();
            LoginDetails ld = JsonConvert.DeserializeObject<LoginDetails>(str);

            if (CheckUser(...)
            {
                return Ok(...);
            }

            return Unauthorized();
        }

It works like a charm. But it seems this is not the only place in the API that now cannot deserialise. So a fix to this would greatly be appreciated.

I have tried [FromBody] and even tried a different server. I have made sure that Angular is sending the content-type application/json. I've also checked to make sure the model lines up with the JSON being sent. I've checked to make sure the AppPool is set to Integrated.

I can take the JSON sent from Angular and POST via postman and it works. It's the combination of Angular (local or hosted) and Web API hosted by IIS that seems to cause the issue.

I'm at a loss so any help would be great. Thanks




Aucun commentaire:

Enregistrer un commentaire