JSON,使用HttpPost获取信息

时间:2016-11-08 10:15:46

标签: c# json visual-studio cross-platform

我在Xamarin表单PCL中重新创建旧的Cordova应用程序,我需要访问服务器上的这种方法,为其提供用户名和密码并存储返回的信息:

[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#中找到关于如何实现这一目标的明确答案

1 个答案:

答案 0 :(得分:0)

这是一个显示我如何进行Post调用的示例。我想如果你改为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();
}