WebAPI学习笔记(3)Asp.net调用WebAPI Post方法传递参数

喜欢而已 提交于 2019-12-02 19:08:37

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、返回结果:

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!