WinForm使用POST请求方式向WebApi传递参数始终为空

文章介绍了在WinForm应用中使用POST方法向WebApi发送JSON数据时遇到的参数接收为空的问题。问题源于参数类型不匹配。解决方案是将WebApi的接收参数改为dynamic类型,然后进行反序列化处理。示例代码展示了如何在WebApi控制器和WinForm客户端进行相应的调整来正确传递和接收JSON数据。

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

案例场景:

WinForm使用POST请求方式向WebApi传递参数


关键词:dynamic
有时候我们抓到⼀段请求数据:JSON格式的字符串数据,我们就可能会⽤dynamic先接受数据,然后再转换成特定数据发出请求。

问题描述:

WinForm向WebApi中使用POST请求方式传参始终为空

WebApi中接收数据代码:
方式1:

[HttpPost]
public string Post(string value)
{
    JsonModel jsonModel = JsonConvert.DeserializeObject<JsonModel>(value);
    return value.ToJsonString();
}

方式2:

[HttpPost]
public string DataIn(JsonModel data)
{
    string value = "数据传入";
    string datain = JsonConvert.SerializeObject(data);
    return value + ": " + datain;
}

原因分析:

传入参数类型与接收参数类型不同,无法获取当前值
从WinForm使用POST向WebApi请求时,传递参数在接收端应使用动态类型(dynamic)接收


解决方案:

接收参数类型使用dynamic类型

[HttpPost]
public string Post(dynamic data)
{
    string value = data.ToString();
    JsonModel jsonModel = JsonConvert.DeserializeObject<JsonModel>(value);
    return value.ToJsonString();
}

完整案例:

———— WebApi ————

Student.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace MyWebAPI.Models
{
    public class Student
    {
        public string Name { get; set; }

        public int Age { get; set; }
    }
}

Teacher.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace MyWebAPI.Models
{
    public class Teacher
    {
        public string Tname { get; set; }

        public int Tage { get; set; }
    }
}

JsonModel.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace MyWebAPI.Models
{
    public class JsonModel
    {
        public Student json1 { get; set; }
        public Teacher json2 { get; set; }
    }
}

WinFormCallController.cs

using MyWebAPI.Extensions;
using MyWebAPI.Models;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;

namespace MyWebAPI.Controllers
{
    public class WinFormCallController : ApiController
    {
    	//方法一 dynamic 
        [HttpPost]
        public string Post(dynamic data)
        {
            string value = data.ToString();
            JsonModel jsonModel = JsonConvert.DeserializeObject<JsonModel>(value);
            return value.ToJsonString();
        }
		//方法二 对象类型(json要规范化与WebApi中的实例要一致时json自动转化为实例)
        [HttpPost]
        public string DataIn(JsonModel data)
        {
            string value = "数据传入";
            string datain = JsonConvert.SerializeObject(data);
            return value + ": " + datain;
        }
    }
}

———— WinfFrom ————
Form1.cs

using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WnFormApiTest
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        JsonModel js;
        //数据写入
        public void DataManage()
        {
            js = new JsonModel() { json1 = new Student(), json2 = new Teacher() };
            js.json1.Name = "Student";
            js.json1.Age = 11;
            js.json2.Tname = "Teacher";
            js.json2.Tage = 22;
        }

        private void Btn_Send_Click(object sender, EventArgs e)
        {
        	//string s = HttpPost("https://localhost:44311/api/WinFormCall?value=", "(写入要传入json字符串)");
            string s = HttpPost(txt_Url.Text, txt_SendMsg.Text);
            Student student = JsonConvert.DeserializeObject<Student>(s);
            int age = student.Age;
            string name = student.Name;
            txt_MesReturnMsg.Text = s;
        }

        public static string HttpPost(string url, string body)
        {
            Encoding encoding = Encoding.UTF8;
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            request.Method = "POST";
            request.Accept = "text/html, application/xhtml+xml, */*";
            request.ContentType = "application/json";
            byte[] buffer = Encoding.UTF8.GetBytes(body);
            request.ContentLength = buffer.Length;
            Stream stream = request.GetRequestStream();
            stream.Write(buffer, 0, buffer.Length);
            //request.GetRequestStream().Write(buffer, 0, buffer.Length);
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            using (StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8))
            {
                return reader.ReadToEnd();
            }
        }

        public static string HttpGet(string url, string body)
        {
            Encoding encoding = Encoding.UTF8;
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            request.Method = "GET";
            request.Accept = "text/html, application/xhtml+xml, */*";
            request.ContentType = "application/json";
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            using (StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8))
            {
                return reader.ReadToEnd();
            }
        }

        private void btnSendGet_Click(object sender, EventArgs e)
        {
            string s = HttpGet(txt_Url.Text, txt_SendMsg.Text);
            txt_MesReturnMsg.Text = s;
        }

        private void btnClassSend_Click(object sender, EventArgs e)
        {
            DataManage();
            string json = JsonConvert.SerializeObject(js);//json序列化
            string s = HttpPost(txt_Url.Text, json);
            txt_MesReturnMsg.Text = s;
            MessageBox.Show("Model调用");
        }
    }
}

特别声明:ToJsonString需要自己定义方法。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值