如何在C#4.0中读取内容类型为application/json的HTTP Post数据
我真的在努力解决一个简单的问题。我们正在接受对API的HTTP帖子。直到今天,当我们试图接近身体时,一切都很好 我们正在尝试接收一个在HTTP头中具有以下值的帖子:content-type:application/json 该值的某些内容导致byteArray只包含NULL值。不过,数组大小仍然正确。只需将内容类型更改为任何其他类型,即可修复问题(application/jso、application\json等),从而触发该值。我们可以接受其他JSON,但不需要那个头值 我们使用的是MVC3,我尝试升级到MVC4,但似乎没有帮助。我们还构建了自己的控制器,但我们不使用内容类型HTTP头执行任何操作。我很感激你能告诉我为什么会发生这种事如何在C#4.0中读取内容类型为application/json的HTTP Post数据,c#,json,asp.net-mvc-3,asp.net-mvc-4,C#,Json,Asp.net Mvc 3,Asp.net Mvc 4,我真的在努力解决一个简单的问题。我们正在接受对API的HTTP帖子。直到今天,当我们试图接近身体时,一切都很好 我们正在尝试接收一个在HTTP头中具有以下值的帖子:content-type:application/json 该值的某些内容导致byteArray只包含NULL值。不过,数组大小仍然正确。只需将内容类型更改为任何其他类型,即可修复问题(application/jso、application\json等),从而触发该值。我们可以接受其他JSON,但不需要那个头值 我们使用的是MVC3,
HttpContextBase httpContext = HttpContext;
if (!httpContext.IsPostNotification)
{
throw new InvalidOperationException("Only POST messages allowed on this resource");
}
Stream httpBodyStream = httpContext.Request.InputStream;
if (httpBodyStream.Length > int.MaxValue)
{
throw new ArgumentException("HTTP InputStream too large.");
}
int streamLength = Convert.ToInt32(httpBodyStream.Length);
byte[] byteArray = new byte[streamLength];
const int startAt = 0;
httpBodyStream.Read(byteArray, startAt, streamLength);
httpBodyStream.Seek(0, SeekOrigin.Begin);
switch (httpContext.Request.ContentEncoding.BodyName)
{
case "utf-8":
_postData = Encoding.UTF8.GetString(byteArray);
代码中的错误似乎是第一行。代码将HttpContext分配给名为HttpContext的局部变量。由于我不知道的原因,通过删除这一行并直接使用HttpContext,代码工作了
if (!HttpContext.IsPostNotification)
throw new InvalidOperationException("Only POST messages allowed on this resource");
HttpContext.Request.InputStream.Position = 0;
if (HttpContext.Request.InputStream.Length > int.MaxValue)
throw new ArgumentException("HTTP InputStream too large.");
int streamLength = Convert.ToInt32(HttpContext.Request.InputStream.Length);
byte[] byteArray = new byte[streamLength];
const int startAt = 0;
HttpContext.Request.InputStream.Read(byteArray, startAt, streamLength);
HttpContext.Request.InputStream.Seek(0, SeekOrigin.Begin);
switch (HttpContext.Request.ContentEncoding.BodyName)
{
case "utf-8":
_postData = Encoding.UTF8.GetString(byteArray);
您可以使用原始的
HttpContext
而不是对流的引用吗
或者可能从堆栈溢出应答获取应用程序实例的上下文
// httpContextBase is of type HttpContextBase
HttpContext context = httpContextBase.ApplicationInstance.Context;
JSON请求的
httpContext.Request.ContentEncoding.BodyName
的值是多少?它是否与附加“;charset=utf-8'我真的不相信它与编码有任何关系。至少据我所知,字节数组在编码之前充满了空值;charset=utf-8,但我无法控制Shopify发送给我的头。看起来只有内容类型:application/json失败。