WebApi使用

来源:互联网 发布:java分布式集群框架 编辑:程序博客网 时间:2024/05/29 07:51

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; }     }




0 0
原创粉丝点击