0

我有一个 Angular 2 登录表单,我正在尝试通过 API 调用调用 JWT 令牌控制器。

我的 user.service.ts 如下:-

login(username, password) {
  let headers = new Headers();
  headers.append('Content-Type', 'application/x-www-form-urlencoded');
  let credentials = JSON.stringify({ username, password });
  console.log(username, password);
  return this._http.post('http://localhost:5000/api/jwt', credentials, { headers: headers })
    .map(res => res.json())
    .map((res) => {
      if (res.success) {
        localStorage.setItem('auth_token', res.auth_token);
        this.loggedIn = true;
      }

      return res.success;
    });
}

当我执行 console.log(username, password); 我在表单中输入了正确的用户名和密码。

然后我有如下控制器: -

      [HttpPost]
  [AllowAnonymous]
  public async Task<IActionResult> Get(string username, string password)
  {

  //code here

  }

我的问题是用户名和密码始终为空。

我曾尝试使用 Postman使用用户名和密码向“ http://localhost:5000/api/jwt ”发帖,并且效果很好。

如何将用户名和密码从 Angular 2 表单传递给控制器​​?

感谢您的帮助和时间

约翰

4

1 回答 1

0

您设置了错误的 Content-Type 标头,它必须是 JSON:

headers.append('Content-Type', 'application/json');

还要确保您创建了一个有效的 JSON 对象(JSON.stringify({ username, password })无效,并且您在控制台上收到一个 javascript 错误,说明它已损坏):

let credentials = JSON.stringify({ username: username, password: password });

最后但并非最不重要的一点是引入一个视图模型来匹配这个结构:

public class LoginViewModel
{
    public string Username { get; set; }
    public string Password { get; set; }
}

您的控制器操作将作为参数:

public async Task<IActionResult> Get(LoginViewModel loginModel)
于 2017-02-23T09:47:05.790 回答