2017-02-23 34 views
0

我有一個角度2登錄表單,我試圖通過API調用來調用JWT令牌控制器。通過Angular 2登錄表單將用戶名和密碼傳遞給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(用戶名,密碼);我在表單中輸入正確的用戶名和密碼。

然後,我有控制器如下: -

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

    //code here 

    } 

我的問題是用戶名和密碼始終爲空。

我試圖用郵遞員給'http://localhost:5000/api/jwt'用用戶名和密碼,它工作正常。

如何將用戶名和密碼從Angular 2表單傳遞給控制器​​?

感謝您的幫助和時間

約翰

回答

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) 
+0

我想你說的達林什麼,改變了我的GET公共異步任務獲取([FromForm] ApplicationUser applicationUser) 但是我仍然在用戶名和密碼都爲空 – Johann

+0

我的ApplicationUser完全像你的LoginViewModel – Johann

+0

你不應該使用'[FromForm]'而是'[FromBody ]'在這種情況下。 –

相關問題