WebApi Post参数对象,服务器端参数对象为空的问题

在研究WebApi时,遇到Post参数对象在服务器端显示为空的困扰。经过午后的一系列调试和同事的帮助,终于找到问题关键:若按照特定方式传递参数,服务器端才能正确接收到值。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

最近在研究WebApi,在实际的工作中遇到了一个问题:在将参数对象MSG2的实例通过Post至服务器端的时候,

 public static string SetMessageOperationResult(MSG2 model)
        {
            string result = string.Empty;
            if (model == null) return result;          
            Hashtable ht = new Hashtable();         
            ht.Add("Authorization", string.Format("Bearer {0}", _accToken));             

            var content = JsonConvert.SerializeObject(model);          
            string url = string.Format("{0}{1}", _baseUrl, _setMessageOperationResult);
            result = HttpHelper.PostData(content, url, _timeout, ht);
            return result;
        }
服务器端接收到的参数实例化结果总是为空:

<pre name="code" class="csharp"> [HttpPost]
        public async Task<MSG2ReturnModels> SetMessageOperationResult(MSG2 MSG2)
        {
         if(MSG2 == null) //一直成立



我一遍又一遍的检查代码,尝试着各种解决办法,包括[FromBody] \ [FromURL] ,各问题依旧。。。。。。

一直到了下午,吃过了午饭,在小伙伴的一次次帮助下,最终我发现了问题的所在:

 public static string SetMessageOperationResult(MSG2 model)
        {
            string result = string.Empty;
            if (model == null) return result;          
            Hashtable ht = new Hashtable();         
            ht.Add("Authorization", string.Format("Bearer {0}", _accToken));             

            var content = JsonConvert.SerializeObject(model);          
            string url = string.Format("{0}{1}", _baseUrl, _setMessageOperationResult);
            result = HttpHelper.PostData(content, url, _timeout, ht, <strong style="background-color: rgb(255, 0, 0);">"application/json", "text/json"</strong>);
            return result;
        }
如果红色的两个参数不传,我的方法默认这两个参数的值为:"application/x-www-form-urlencoded"  和   "application/json",则服务器端将会获取不到客户端传递过来的值


如果按照红色的值进行传递,那么服务器端参数对象就会接收到下图的说要传递的值,


   public static string PostData(string request, string url, int timeout, Hashtable ht, string reqType = "application/x-www-form-urlencoded", string resType = "application/json")
        {

            string responseString = string.Empty;
            HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(url);
            webRequest.ContentType = reqType;// + ";charset=\"utf-8\""
            webRequest.Accept = resType;// resType;

            webRequest.Method = "POST";
            webRequest.Timeout = timeout * 1000;


            try
            {


                foreach (DictionaryEntry de in ht)
                {
                    webRequest.Headers.Add(de.Key.ToString(), de.Value.ToString());
                }
                byte[] bytes = Encoding.GetEncoding("utf-8").GetBytes(request);
                webRequest.ContentLength = bytes.Length;
                webRequest.GetRequestStream().Write(bytes, 0, bytes.Length);
                HttpWebResponse response;//= (HttpWebResponse)webRequest.GetResponse();
                try
                {
                    response = (HttpWebResponse)webRequest.GetResponse();
                }
                catch (WebException ex)
                {

                    response = (HttpWebResponse)ex.Response;
                    using (StreamReader reader = new StreamReader(response.GetResponseStream(), System.Text.Encoding.GetEncoding("utf-8")))
                    {
                        responseString = reader.ReadToEnd();
                    }
                    throw new Exception(responseString);
                }


                using (StreamReader reader = new StreamReader(response.GetResponseStream(), System.Text.Encoding.GetEncoding("utf-8")))
                {
                    responseString = reader.ReadToEnd();
                }

                return responseString;
            }

            catch (Exception ex)
            {

                throw new Exception(ex.Message);
            }
        }




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值