KonRow
KonRow

Reputation: 63

Angular post request to c# web api 2 RESTful web service

I'm trying to send a http post request from angular client to C# web API 2 RESTful web service.

My client:

var userId = "123456";
var password = "654321";

const headersContent = new Headers().set('Content-Type', 'application/x-www-form-urlencoded');
var url = "http://localhost:35615/login"
this.http.post(url, {
    "userId": userId,
    "password": password
}, {withCredentials: true}).subscribe(res => {
    console.log(res);
});

My Server:

[Route("login")]
[HttpPost]
public IHttpActionResult LoginReq([FromBody] string parameters)
{
    //Deserialize the parameters.
}

My problem is the parameters var is null although the post request in the network tab in chrome includes the data.

Can someone explain me what I'm doing wrong and how can I fix it? Thank you!

Upvotes: 1

Views: 3373

Answers (4)

Julpe
Julpe

Reputation: 105

You are passing an anonymous object with properties "UserId" and "Password". Make a Data Contract class which has those 2 properties as strings and use it in the parameters of your REST method.

public IHttpActionResult LoginReq([FromBody] User user) { ... }

Upvotes: 2

Karthik
Karthik

Reputation: 31

If you are passing an object from your Angular POST request the Web API POST method can be changed to accept an User defined type as parameter to read it from the request body.

You can create the below user defined type in C# to bind UserId and Password properties from your angular Post request

public class UserLogin
{
    public int UserId { get; set; }
    public string Password { get; set; }
}

[Route("login")]
[HttpPost]
public IHttpActionResult LoginReq([FromBody] UserLogin user)
{
    //Deserialize the parameters.
}

I would recommend going through this documentation to read more about parameter binding in Web API. Believe me its worth your time.

Upvotes: 1

Rahul
Rahul

Reputation: 2128

Just add JSON.stringify() you are sending an object to the server which expects only a string as a parameter so make it as a string and pass the value otherwise create a model with userid and password in your server side and mention that object

let obj =  {
        "userId": userId,
        "password": password
    };   
this.http.post(url, JSON.stringify(obj), {withCredentials: true}).subscribe(res => {
        console.log(res);
    });

The above code will work with the string parameters - Going forward try to use model and pass the object from Angular

Happy Coding !!

Upvotes: 0

user10608712
user10608712

Reputation:

You post userId and password, but expect String parameters. Change to String userId, String password. The Modelbinder only will bind matching properties.

Upvotes: 0

Related Questions