asp.net接收API Post Json数据为空要注意的事项

  • asp.net接收API Post Json数据为空要注意的事项已关闭评论
  • 144 次浏览
  • A+
所属分类:.NET技术
摘要

今天在处理一个接收API通过Post方式传送Json数据的方法时,碰到接收的Json数据一直是空的问题。最好找了好久才解决,现在把需要的问题列出来。

今天在处理一个接收API通过Post方式传送Json数据的方法时,碰到接收的Json数据一直是空的问题。最好找了好久才解决,现在把需要的问题列出来。

 

1. 在一般处理程序中,需要设置  context.Request.InputStream.Position = 0;  刚开始设置了这个,但后面还是为空,原因是每二点。

2.在web.config文件,sessionState  要去掉 cookieless="AutoDetect" ,否则就算设置了第一点也还是会为空, 按下面的格式去写

<sessionState mode="InProc" cookieless="false" timeout="20" />

=========================================================

参考的IHttpHandler源代码如下:

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.IO;
using System.Web;
using System.Text;
using System.Web.Script.Serialization;

// 接收 API 通过 Post 方式传送 Json格式的数据

public class GetIPN : IHttpHandler
{

public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "application/json";
context.Response.Cache.SetCacheability(HttpCacheability.NoCache);

string jsonText = string.Empty;

context.Request.InputStream.Position = 0; //这一句很重要,不然一直是空

StreamReader sr = new StreamReader(context.Request.InputStream);
jsonText = sr.ReadToEnd();

 // IPNinfo model = (new JavaScriptSerializer()).Deserialize<IPNinfo >(jsonText);  //转化成实体对象

 //然后去处理业务

context.Response.ContentType = "text/plain";
context.Response.Write("OK"); //API回调响应,如需要返回OK
}

public bool IsReusable
{
get
{
return false;
}
}
}
}

 

工具Json转化为实体类:

https://www.bejson.com/convert/json2csharp/