WebAPI学习笔记(3)Asp.net调用WebAPI Post方法传递参数
1、WebAPI方法:
[HttpPost] public HttpResponseMessage ImportIssue(dynamic obj) { MethodReturnModel<string> returnModel = new MethodReturnModel<string>(); IssueModel issueModel = new IssueModel(); try { string IssueJsonStr = obj.IssueJson.ToString(); issueModel = ConvertJson.JsonToObject<IssueModel>(IssueJsonStr); if(issueModel == null || string.IsNullOrWhiteSpace(issueModel.IssueKey)) { returnModel.Result = false; returnModel.Message = "The json string of issue is not correct"; } else { IssueBLL issueBLL = new IssueBLL(AdminUserToken); string ErrorMessage = ""; if (issueBLL.CreateGPISIssue(issueModel, ref ErrorMessage) > 0) { returnModel.Result = true; } else { returnModel.Result = false; returnModel.Message = ErrorMessage; } } } catch(Exception ex) { returnModel.Result = false; returnModel.Message = ex.Message; } return MethodHelper.GetHttpResponseMessage(ConvertJson.GetJson<MethodReturnModel<string>>(returnModel)); }
2、调用方式:
string Username = "xxx"; string Password = "xxx"; string Body = "{'IssueJson': { 'IssueKey': '009','IssueType': '111'}}"; using (HttpClient client = new HttpClient()) { client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(Encoding.UTF8.GetBytes($"{Username}:{Password}"))); HttpContent httpContent = new StringContent(Body, Encoding.UTF8); httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/json"); Uri address = new Uri("https://localhost:44300/api/issue/ImportIssue"); var response = client.PostAsync(address, httpContent).Result.Content.ReadAsStringAsync().Result;//返回值 }
3、返回结果:
【原文出处】http://www.51aras.com/?id=41