簡體   English   中英

如何從 Angular 請求 c# controller 中的參數? (沒有 url 串聯)

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

我有一個一般性問題,我似乎無法在其他主題中找到任何答案。 所以我將在這里展示我的代碼:這是我的 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)
    );

這是我的 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();

    ...

}

我的問題是:如何將 email 的輸入值和密碼從 angular 傳遞到 c#? 每次在我的 controller 中,我都會得到“”。

你可以做的是使用HttpParams這似乎更干凈的解決方案來解決你的問題

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

最后你會得到這個代碼

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

提琴手

只需在您的后端創建一個 model 以將其傳遞給您的 controller,類似於:

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

在你的 controller 你通過它

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

    ...

}

請注意,我們正在添加[FromBody]屬性來告訴 asp 內容不是作為 url 參數的一部分出現的

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM