Search code examples
c#angularcontrollerhttp-request-parameters

How can I request parameters in c# controller from Angular? (no url concatenation)


I have a general question and I can't seem to find any answer in other topics. So I'll show my code here: This is my register.component.ts:

email = this.registerForm.controls['email'].value;
password = this.registerForm.controls['password'].value;
// call RegisterController
    this.http.post('api/register', params).subscribe(params => {
      this.router.navigate(['']); // redirect to login
    },
      error => console.log(error)
    );

This is my C# Controller:

[Route("api/register")]
[HttpPost]
public void Register(string email = "", string password = "")
{
    email = Request.Query["email"].ToString().Trim();
    password = Request.Query["password"].ToString().Trim();

    ...

}

My question is: how can I pass input values for email and password from angular to c#? Everytime in my controller I get "".


Solution

  • Just create a model in your backend to pass it to your controller, something like:

    public class RegisterModel {
        public string Email { get; set; }
        public string Password { get; set; }
    }
    

    and in your controller you pass it

    public void Register([FromBody]RegisterModel model)
    {
        email = model.Email;
        password = model.Password;
    
        ...
    
    }
    

    Note that we are adding [FromBody] attribute to tell asp that the content is not coming as part of the url params