2016-11-08 54 views
0

我正在Xamarin表單PCL中重新創建一箇舊的Cordova應用程序,並且需要訪問服務器上的此方法,爲其提供用戶名和密碼並存儲返回的信息:JSON,使用HttpPost獲取信息

[HttpGet] 
public JsonResult LoginUser(string userName, string password) 
{ 
    bool responseResult = false; 
    IEBUser user = null; 
    string errMsg = String.Empty; 
    try 
    { 
     if (String.IsNullOrEmpty(userName)) 
     { 
      throw new Exception("userName is Empty"); 
     } 
     else if (String.IsNullOrEmpty(password)) 
     { 
      throw new Exception("userName is Password"); 
     } 

     // connect to DB and find the user if it can 
     user = SelfServiceMembership.GetUserByUserName(userName); 

     // if no suer then user wasn't found or DB Errored 
     if (user == null) 
     { 
      throw new Exception("userName was not found"); 
     } 

     // decrypt pw and see if they match with username's account 
     PasswordHash PH = new PasswordHash(); 
     password = PH.GenerateHash(password); 

     if (user.HashWord != password) 
     { 
      throw new Exception("Password does not match the one on our records"); 
     } 
     responseResult = true; 
    } 
    catch (Exception ex) 
    { 
     errMsg = ex.Message; 
    } 

    if (responseResult) 
    { 
     return Json(new 
     { 
      result = responseResult, 
      user = new 
      { 
       userId = user.UserID, 
       userName = user.UserName, 
       firstName = user.FirstName, 
       lastNmae = user.LastName, 
       email = user.Email 
      } 
     }, 
     JsonRequestBehavior.AllowGet); 
    } 
    return Json(new 
    { 
     result = responseResult, 
     errorMessage = errMsg 
    }, 
    JsonRequestBehavior.AllowGet); 

} 

舊的Javascript代碼調用此方法是這樣的:

// gets user info from web service 
loginUser: function (userName, password){ 
    responseData = null; 
    $.ajax({ 
     type: "GET", 
     url : app.CurrentCompanyDetails.WebServiceURL + this.apiRoot + this.loginUserCall, 
     dataType: "json", 
     data: { 
      userName: userName, 
      password: password 
     }, 
     async: false, 
     crossDomain: true, 
     success: function(response) { 
      responseData = response; 
     }, 
     error: function (xhr, status, msg) { 
      alert(msg); 
     } 
    }); 
    return responseData; 
}, 

我似乎無法在任何地方找到一個明確的答案如何做到這一點在C#

+0

你嘗試改變'HttpGet'爲'HttpPost'和'類型: 「GET」''爲類型: 「POST」'? –

+0

@FabricioKoch對不起,我不知道你在說什麼。 JavaScript代碼需要用C#編寫。 – connersz

+0

對不起。我認爲你正在嘗試修復你的javascript調用。 –

回答

0

這裏是一個顯示我如何進行郵政通話的例子。我想如果你更改爲HttpMethod.GET它也應該工作。

我的示例將userNamepassword發送到REST API,如果一切正常,它會從響應中返回Cookie。您可以更改它以適應您的需求。

private static Cookie ConfigurarAcessoGED() { 
    Uri uri = new Uri("URL_FROM_API"); 
    var req = new HttpRequestMessage(HttpMethod.Post, uri); 
    var reqBody = @"{ 
     'UserName':'USERNAME', 
     'Password':'PASSWORD' 
    }"; 
    req.Content = new StringContent(reqBody, Encoding.UTF8, "application/json"); 

    CookieContainer cookies = new CookieContainer(); 
    HttpClientHandler handler = new HttpClientHandler(); 
    handler.CookieContainer = cookies; 
    HttpClient client = new HttpClient(handler); 
    client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); 
    client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/xml")); 
    HttpResponseMessage resp = null; 
    try { 
    resp = client.SendAsync(req).Result; 
    } catch (Exception ex) { 
    throw new Exception("Something went wrong"); 
    } 
    if (!resp.IsSuccessStatusCode) { 
    string message; 
    if (resp.StatusCode == HttpStatusCode.Unauthorized || resp.StatusCode == HttpStatusCode.Forbidden || resp.StatusCode == HttpStatusCode.Redirect) 
     message = "Permission denied."; 
    else 
     message = resp.ReasonPhrase; 

    throw new Exception(message); 
    } 

    IEnumerable<Cookie> responseCookies = cookies.GetCookies(uri).Cast<Cookie>(); 
    if (responseCookies.FirstOrDefault() != null) 
    return responseCookies.FirstOrDefault(); 
    return null; 
} 

這裏是我的API我的方法:

[HttpPost, Route("LogIn")] 
public IActionResult LogIn([FromServices] UserService userService, [FromBody]LoginModel login) { 
    using (var session = SessionFactory.OpenSession()) 
    using (var transaction = session.BeginTransaction()) { 
    User user = userService.Login(session, login.UserName, login.PassWord); 
    if (user == null) 
     return BadRequest("Invalid user"); 

    var identity = new ClaimsIdentity("FileSystem"); 

    identity.AddClaim(new Claim(ClaimTypes.Name, login.UserName)); 
    foreach (Role r in user.Roles) { 
     identity.AddClaim(new Claim(ClaimTypes.Role, r.Nome)); 
    } 
    var principal = new ClaimsPrincipal(identity); 
    HttpContext.Authentication.SignInAsync("FileSystem", principal).Wait(); 
    } 
    return Ok(); 
}