2

I'm working in Angular 5 and Asp.Net Web API

In angular I have service and component, so component receive parameter from view like this:

forgotPass() {

    this.loading = true;
    debugger;
    this._authService.forgotPassword(this.model.email).subscribe(
      data => {
        this.toastr.success("Sended success")
        this.loading = false;
        LoginCustom.displaySignInForm();
        this.model = {};
      },
      error => {
        this.showAlert('alertForgotPass');
        this._alertService.error(error);
        this.loading = false;
      });
  }

and service execute controller like this:

forgotPassword(email: string) {
    let headers = new Headers({ 'Content-Type': 'application/json' });
    let options = new RequestOptions({ headers: headers });

    return this.http.post(this.rootUrl + '/ChangePasswordToken', JSON.stringify({ email: email }), options)
      .map((response: Response) => {

      });
  }

As you can see I send parameter email to WebApi, problem is controller receive it as null, but when I debbugging JS it send email success:

enter image description here

Controller:

  [Route("ChangePasswordToken")]
        public async Task<IActionResult> GeneratePasswordChangeToken(string email)
        {//code there}

Why I always get null in controller if angular sended it correctly? Regards

David Walschots
  • 12,279
  • 5
  • 36
  • 59
David
  • 1,035
  • 1
  • 7
  • 11

2 Answers2

2

When you declare the client model as { email: email } you are defining an object that will be sent to the server. But on the server side you expect a string.

To solve this, you could:

Either define a C# model which matches the client model

public class EmailModel
{
    public string Email { get; set; }
}

Then read the model from the request body in the api method

[Route("ChangePasswordToken")]
public async Task<IActionResult> GeneratePasswordChangeToken([FromBody]EmailModel model)
{//model.Email }

Or, change the signature of the client model to be just a =string

this.http.post(this.rootUrl + '/ChangePasswordToken', JSON.stringify({ email: email }), options) to this.http.post(this.rootUrl + '/ChangePasswordToken', "=" + email, options) then read the string from the request body

[Route("ChangePasswordToken")]
public async Task<IActionResult> GeneratePasswordChangeToken([FromBody]string email)

Here's another answer on reading string directly from the body

Marcus Höglund
  • 16,172
  • 11
  • 47
  • 69
0

You are trying to pass a JSON object as param and try to receive it as a string. Hence it fails.

If you want to send a single string a param, you could try forms encoding like below:

change the content type to

contentType: 'application/x-www-form-urlencoded'

and request should be:

this.http.post(this.rootUrl + '/ChangePasswordToken', "=" + email, options)