0

The code below, which is summarized for better understanding, works perfectly with LOCALHOST, however, when I put it in IIS, the body of the request always arrives EMPTY. Can someone help me?

Client application code:

  login(userName: string, password: string): Observable<User> {

    const headers = new HttpHeaders({
      'Content-Type': 'application/json'
    });

    return this.http.post(`${environment.API_URL}/profiles/login`,
      { userName, password }, { headers }
    ).pipe(
      tap((currentUser: User) => {
        this.updateUser(currentUser)
          .then(
            () => {
              console.log('currentUser login stored: ', AppSettings.currentUser);
            },
            error => console.error('Error storing currentUser login', error)
          );
        return AppSettings.currentUser;
      }),
    );
  }

ASP.NET Core 3.1 application code on the server:

    [Route("api/[controller]")]
    [ApiController]
    public class ProfilesController : ControllerBase
    {
        [HttpPost("login")]
        public async Task<ActionResult> Login(LoginRequest request)
        {
            try
            {
                using (var Reader = new StreamReader(Request.Body, Encoding.UTF8))
                {
                    var sb = new StringBuilder();

                    sb.AppendFormat("ContentType: {0}\n", Request.ContentType);
                    sb.AppendFormat("Request: {0}\n", Request.ToString());
                    sb.AppendFormat("ContentLength: {0}\n", Request.ContentLength.ToString());
                    if (Request.IsHttps)
                        sb.AppendFormat("{0}\n", "HTTPS!");

                    var headers = String.Empty;
                    foreach (var key in Request.Headers)
                        headers += key.Key + "=" + key.Value + Environment.NewLine;
                    sb.AppendFormat("Headers: \n{0}\n", headers);

                    sb.AppendFormat("QueryString: {0}\n", Request.QueryString);

                    var text = await Reader.ReadToEndAsync();
                    sb.AppendFormat("Body: {0}\n", text);
                    return Ok(sb.ToString());
                }
                return Ok("OK");
            }
            catch (System.Exception ex)
            {
                return Unauthorized($"{ex.Message}: {ex.StackTrace}");
            }
        }
    }

Request result:

ContentType: application/json
Request: Microsoft.AspNetCore.Http.DefaultHttpRequest
ContentLength: 79
Headers: 
Accept=*/*
Accept-Encoding=gzip, deflate, br
Cache-Control=no-cache
Connection=keep-alive
Content-Length=79
Content-Type=application/json
Host=loja.online
User-Agent=PostmanRuntime/7.22.0
Postman-Token=121f1927-c340-492f-a98b-0d6586ff32d8

QueryString: 
Body: 

Using POSTMAN the same thing happens!

Postman POST

RequestLogin class

jps
  • 20,041
  • 15
  • 75
  • 79
Marcius Bezerra
  • 137
  • 1
  • 2
  • 11
  • Did you hit the `Login` method when hosted on IIS? – Rena Feb 17 '20 at 02:25
  • Could you check what is the request from browser network tab? Besides, what is `LoginRequest`? – Rena Feb 17 '20 at 09:31
  • Sory, In the Postman i not have this tab – Marcius Bezerra Feb 17 '20 at 17:10
  • Can you please add [FromBody] on your Action method next to the LoginRequest and try again? – Mosia Thabo Feb 18 '20 at 00:24
  • Hi @MarciusBezerra,you receive the `LoginRequest` and it would read the body for first time,then you read it again in your method,so your body is empty.For read body more than once,you could refer to [here](https://stackoverflow.com/a/58742076/11398810).Could you share a sample that could reproduce your issue? – Rena Feb 18 '20 at 09:07

1 Answers1

1

Try Specifying the source:

    public async Task<ActionResult> Login([FromBody] LoginRequest request) //Added [FromBody]

Just for Further Details

Mosia Thabo
  • 4,009
  • 1
  • 14
  • 24
  • 1
    thanks! It worked! I just didn't understand why the [FromBody] since I'm using ApiController attribute. – Marcius Bezerra Feb 28 '20 at 14:04
  • Makes sense. ApiController attribute just decorate your controller. basically telling your app that this is an api controller and must be treated as such. – Mosia Thabo Feb 28 '20 at 21:25
  • I tried by adding [FromBody] attribute, but didn't work for me. Any other fix please? – Raj K May 07 '21 at 02:51
  • The only way I could help is if I see your code. Because it may be that the body is not being submitted to the backend... – Mosia Thabo May 07 '21 at 09:37
  • @RajK try `[FromForm]`. Both [FromForm] and [FromBody] assume the web method's data will be found in the request body. `[FromForm]` is best when the data arrives as Form data (name-value pairs, older HTML style forms). `[FromBody]` is best when the body data arrives as JSON (usually from some JavaScript framework). – Zarepheth Aug 31 '21 at 20:22
  • @Zarepheth It's best to say `[FromBody]` is for data submitted via Ajax as body property. Which presumably will be a JSON string... A Form data may also arrive in JSON format but the back-end will only know based on Request Headers, not the data itself. – Mosia Thabo Sep 02 '21 at 22:38
  • @Zarepheth thanks for your comment. I solved it by somehow using `[FromBody]`. Thank you – Raj K Sep 21 '21 at 03:07