JSON,使用HttpPost获取信息

本文关键字:获取 信息 HttpPost 使用 JSON | 更新日期: 2023-09-27 18:16:51

我在Xamarin forms 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#中实现这一点,我似乎找不到一个明确的答案

JSON,使用HttpPost获取信息

下面是一个示例,展示了我如何进行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();
}