2013-12-10 50 views
2

好的,所以我試圖讓我的頭圍繞web api,並且我想創建一個mokup登錄頁面,它向驗證控制器發佈用戶名和密碼。但是,我不似乎在我的崗位要得到任何東西html表單發佈到web api 2控制器

Post null

這隨後導致問題,當我嘗試在我的控制器驗證usernaem和密碼:

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

public class AuthenticationController : ApiController 
{ 
    /// <summary> 
    /// Creates an authenticated session. If successfully authenticated returns   a 'Set-Cookie' header 
    /// containing the cookie for future requests. On failed login attempt an HTTP 
       401 error is returned. 
    /// </summary> 
    [HttpPost, AllowAnonymous] 
    [Route("api/login")] 
    public HttpResponseMessage Login([FromBody]LoginCredentials credentials) 
    {   
     Logout(); 
     credentials.Username = credentials.Username ?? string.Empty; 
     credentials.Password = credentials.Password ?? string.Empty; 

     var authResult = Authentication.Authenticate(credentials.Username, 
          credentials.Password); 
     if (authResult == null || authResult.User == null) 
      return Authentication.GetUnauthorisedResponse(); 
     if (!authResult.UseAllowed) 
      return Authentication.GetNotUseAllowedResponse 
          (authResult.Status); 

     var authenticationManager = Request.GetOwinContext().Authentication; 
     authenticationManager.SignIn(authResult.User.ToIdentity()); 

     return new HttpResponseMessage(HttpStatusCode.NoContent);; 
    } 
    } 

我的形式從而看起來像:

<form autocomplete="off" method="post" action="/api/login" name="myLogin"> 

    <fieldset> 
     <legend>Login credentials</legend> 

     <div class="form-group"> 
      <label for="Username">Username</label> 
      <input id="Username" type="text" /> 
     </div> 

     <div> 
      <label for="Password">Password</label> 
      <input id="Password" type="password" /> 
      <span class="help-block" data-validation="Password"></span> 
     </div> 

     <div class="form-group center"> 
      <button type="submit" class="btn btn-primary" data-disable-on-submit="true">Log 
       on</button> 
     </div> 
    </fieldset> 
</form> 

不知道我沒那麼正確。

回答

2

您是否嘗試給輸入name屬性值與視圖模型屬性名稱相同?

<input id="Username" name="Username" type="text" /> 

這會將表單發佈的數據綁定到視圖模型對象。

+1

賓果,名稱屬性工作的一種享受。乾杯 – CSharpNewBee

相關問題