webapi接口接收请求获取不到参数的问题

最近政府那边做了一个不动产过户给水电气热推送过户信息得接口。

用了C# webapi

被动接收来自不动产和大数据那边的推送数据,给了数据格式。做完之后与那边技术对接一头包暂且不提。

期间发现接收的请求都获取不到参数,在排除自身问题的时候,尝试了多种方法。

最终问题解决如下:

[HttpPost]
[Route("~/xxxx")]
public object xxxx()
{
    Stream s = HttpContext.Current.Request.GetBufferedInputStream();
    byte[] b = new byte[s.Length];
    s.Read(b, 0, (int)s.Length);
    string a = Encoding.UTF8.GetString(b);
}

期间尝试了

public object pushDjData(dynamic obj)

public object pushDjData([FromBody]zhuang obj)

都不好用

对方直接给了请求的java代码

	public static String post(String strURL,String params) {
		try{
			URL url = new URL(strURL);
			HttpURLConnection connection = (HttpURLConnection) url.openConnection();
			connection.setDoOutput(true);
			connection.setDoInput(true);
			connection.setUseCaches(false);
			connection.setInstanceFollowRedirects(true);
			connection.setConnectTimeout(60000);
			connection.setReadTimeout(60000);
			connection.setRequestMethod("POST");
			connection.setRequestProperty("Accept", "application/x");
			connection.setRequestProperty("Content-Type", "application/json");
			connection.connect();
			OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream(), "UTF-8");
			out.append(params);
			out.flush();
			out.close();

			int length = connection.getContentLength();
			InputStream is = connection.getInputStream();
			if(length != -1){
				byte[] data = new byte[length];
				byte[] temp = new byte[512];
				int readLen = 0;
				int destPos = 0;
				while ( (readLen = is.read(temp)) > 0){
					System.arraycopy(temp, 0, data, destPos, readLen);
					destPos += readLen;
				}
				return new String(data, "UTF-8");
			}
		}catch (IOException e){
			System.out.println(e.getMessage());
			if("Connection timed out: connect".equals(e.getMessage())){
				return "no connect";
			}
			e.printStackTrace();
		}
		return "error";
	}

值得一提的是

Stream s = HttpContext.Current.Request.GetBufferedInputStream();

一开始写法是

 Stream s = HttpContext.Current.Request.InputStream;

报了错误

在 HttpRequest.GetBufferedInputStream 的调用方填充内部存储之前访问了 BinaryRead、表单、文件或 InputStream;

通过流的方式是否可以取到body里面的请求参数,我跟我同事测试结果不一致,有待后期发现。

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值