WebApi使用

4 篇文章 0 订阅

post访问webapi时,要求:被访问的action名称必须以post开头;使用httpclient 发送post请求或者是jquery

代码:

使用httpclient发送post请求:

        /// <summary>
        /// post请求 webapi
        /// </summary>
        /// <param name="url"></param>
        /// <param name="postData"></param>
        public static async void DooPost(string url, Dictionary<string, string> postData)
        {
            //设置HttpClientHandler的AutomaticDecompression
            var handler = new HttpClientHandler() { AutomaticDecompression = DecompressionMethods.GZip };
            //创建HttpClient(注意传入HttpClientHandler)
            using (var http = new HttpClient(handler))
            {
                //使用FormUrlEncodedContent做HttpContent
                var content = new FormUrlEncodedContent(postData);
                //await异步等待回应
                var response = await http.PostAsync(url, content);
                //确保HTTP成功状态值
                response.EnsureSuccessStatusCode();
            }
        }
var postData= new Dictionary<string, string>()
                {    {"SubscriptionId",subscriptionId.ToString()},
                     {"TempMsg",tempmsg},
                     {"TenantId", tenantId.ToString()},
                      {"UserId", userid.ToString()}//键名必须为空
                 };
 

WebApi接收方:

       public string PostTemplateMsg([FromBody]WeChatTempParams paramdic)

        {
            string result = "-1";
            try
            {
                if (paramdic != null)
                {
                    if (CheckUser(paramdic.TenantId, paramdic.UserId))
                    {
                        result = WeChatApi.SenTemMsg(paramdic.TempMsg);
                        WeChatTemResult resulmodel = JsonConvert.DeserializeObject<WeChatTemResult>(result);
                        result = resulmodel.errmsg;
                    }
                    else
                    {
                        result = "No operation permissions";
                    }
                }
                else
                {
                    result = "Parameter is invalid";
                }
            }
            catch (Exception ex)
            {
                _log.Error(ex);
            }
            return result;
        }
 public class WeChatTempParams
    {
        public Guid SubscriptionId { get; set; }
        public string TempMsg { get; set; }
        public int TenantId { get; set; }
        public int UserId { get; set; }
     }

 



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值