Angular2 Http post request not binding to ASP.NET 5 controller's action

I am initiating a post request from Angular2 to a ASP.NET 5 controller action. Angular is posting the data correctly and hitting the controller action but it is not being mapped to the parameters defined in controller action, the parameters are null. Meanwhile by inspecting through Request object Request.Form has the correct textual data but not binding to the model.

Angular

let body = JSON.stringify({ firstName: 'Ali' });
let headers = new Headers({ 'Content-Type': 'application/x-www-form-urlencoded' });

this.http.post(this.url, body, { headers: headers })
            .subscribe(
                (data) => {
                    console.log('Response received');
                    console.log(data);
                },
                (err) => { console.log('Error'); },
                () => console.log('Authentication Complete')
            );

ASP.NET

[HttpPost]
public IActionResult DemoAction(string firstName)
{
      var req = Request;

      return null;
}

Request.Form has data in the form like {\"firstName\":\"Ali\"} but the parameter firstName is null

Answers


You try to send a JSON content (created using the JSON.stringify method) with a content type url encoded form.

You should try to use the application/json one:

let body = JSON.stringify({ firstName: 'Ali' });
let headers = new Headers({ 'Content-Type': 'application/json' });

this.http.post(this.url, body, { headers: headers })

Edit

If you want to provide a form content, you could leverage the URLSearchParams class:

var params = new URLSearchParams();
params.set('firstName', 'Ali');
let headers = new Headers({ 'Content-Type': 'application/x-www-form-urlencoded' });

this.http.post(this.url, params.toString(), { headers: headers })

In this case you don't require to pass the header. look at here. you may try this.

this.http.post('/api/ControllerName/DemoAction?firstName=Ali')
.subscribe(
                (data) => {
                    console.log('Response received');
                    console.log(data);
                },
                (err) => { console.log('Error'); },
                () => console.log('Authentication Complete')
            );

This will surely work.


Edited:

Figured out your problem.

First: When you are receiving paramter(s) at API end , you must use above portion.

second: When you are receiving object at API end, you must use below code.

I'm showing you with my setup as I don't know your object at server side.

let um=JSON.stringify({ Username: "Hello1",Password:"Hello2"});

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

this.http.post(this.url+'/Authentication',um,{ headers: headers })
                        .subscribe(...);

At server side I have following setup.

public class UserModel
{
    public string Username { get; set; }
    public string Password { get; set; }
}

[HttpPost]
public IHttpActionResult Authentication(UserModel um)  // I m getting value here.
{
    if (um.Username == "a" && um.Password == "a")
    {
        um.Username = um.Username;
        um.Password = um.Password;
        return Ok(um);
    }
    return NotFound();
}

Simple solution !! isn't it?


For me it works:

let headers = new Headers({ 'Content-Type': 'application/json' });
this.http.post(this.url, JSON.stringify({ firstName: 'Ali' }), { headers: headers })

Need Your Help

How to make responsive logo inside navbar in Boot Strap3

twitter-bootstrap-3

I am creating a navbar with fixed top. Want the logo to be responsive inside nav bar.