简体   繁体   中英

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 "".

what you can do is to use HttpParams which seem more clean solution to solve you problem

let httpParams = new HttpParams()
    .append("email", "test@test.com")
    .append("password", "Password1");

in the end you will get this code

email = this.registerForm.controls['email'].value;
password = this.registerForm.controls['password'].value;

let httpParams = new HttpParams()
    .append("email", email)
    .append("password", password);

// call RegisterController
this.http.post('api/register', httpParams).subscribe(params => {
    this.router.navigate(['']); 
    },
     error => console.log(error)
);

You can create a model in asp.net webapi and send the data from angular as json (content-type:application/json) and let web api formatter deserialize it to your model object

ASP.NET 网络 API

提琴手

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM