IHttpClientFactory Get和Post

  public class LoginController : Controller
    {
        private readonly IHttpClientFactory _clientFactory;
        public LoginController(IHttpClientFactory clientFactory)
        {
            _clientFactory = clientFactory;
        }
        public IActionResult Index()
        {
            return View();
        }
        public async Task<IActionResult> Login(string username,string pwd)
        {
            //todo:调用id4server获取token
            string token = await GetToken(username, pwd);
       
            ResultDto<string> resultDto = new ResultDto<string>();
            resultDto.Data = token;
            resultDto.StatusCode = ResultCodes.OK;
            resultDto.Message = "操作成功";
            return Json(resultDto);
        }
        /// <summary>
        /// 调用id4server获取token
        /// </summary>
        /// <param name="username"></param>
        /// <param name="pwd"></param>
        /// <returns></returns>
        private async Task<string> GetToken(string username, string pwd)
        {
           
            var client = _clientFactory.CreateClient();
//传输json格式
// var content= new StringContent("xxx=xxx", Encoding.UTF8,"application/json");
// 模拟表单提交
var content = new StringContent($"client_id=user_clientid&client_secret=user_secret&grant_type=password&username={username}&password={pwd}", Encoding.UTF8, "application/x-www-form-urlencoded"); var httpResponse = await client.PostAsync($"http://localhost:5000/connect/token", content); var jsonData= await httpResponse.Content.ReadAsStringAsync(); AuthModel model = JsonConvert.DeserializeObject<AuthModel>(jsonData); return model.access_token; } }

 

posted @ 2021-04-06 17:13  幸福安康  阅读(769)  评论(0编辑  收藏  举报