反序列化HTTP POST内的对象 [英] Deserializing the object inside an http post
问题描述
您好我想从attribute.I正在使用的ASP.NET Web API框架的授权内的HttpPost方法调用反序列化对象。
下面是我的code:
公共覆盖无效OnAuthorization(HttpActionContext ActionContext中)
{ VAR rezult = DeserializeStream<EvaluationFormDataContract>(actionContext.Request.Content.ReadAsStreamAsync().Result); } 私人ŧDeserializeStream&LT; T&GT;(流流)
{
VAR的BinaryFormatter =新的BinaryFormatter(); VAR苏亚雷斯= binaryFormatter.Deserialize(流); VAR T =(T)binaryFormatter.Deserialize(流);
返回吨;
}
在此code被执行我得到这个异常时的BinaryFormatter tryes反序列化的:
输入流不是有效的二进制格式。起始内容(以字节为单位)有:73-74-75-64-65-6E-74-41-73-73-69-67-6E-6D-65-6E-74 ...
块引用>我在做什么错了?
解决方案您尝试使用
的BinaryFormatter
来这是不是二进制序列化的二进制数据的反序列化。从数据你送我看到十六进制code再presents的字符串。
73-74-75-64-65-6E-74-41-73-73-69-67-6E-6D-65-6E-74
德$ C $光盘studentAssignment
这使我相信你在做一个简单的AJAX调用和发送JSON数据的WebAPI服务。
您需要使用JSON反序列化流。
- 读取请求内容字符串
- 如果内容为JSON,使用JSON.NET反序列化
VAR JSON = actionContext.Request.Content.ReadAsStringAsync()结果;
变种M = JsonConvert.DeserializeObject&LT; EvaluationFormDataContract&GT;(JSON);如果反应不JSON,但表单数据可以解析它像一个查询字符串。
VAR StringData是= actionContext.Request.Content.ReadAsStringAsync()结果;
NameValueCollection中的数据= HttpUtility.ParseQueryString(StringData是);
串PERSONID =数据[PERSONID];Hi I am trying to deserialize an Object from a HttpPost method call inside an authorize attribute.I am using ASP.NET Web Api Framework.
Here is my code:
public override void OnAuthorization(HttpActionContext actionContext) { var rezult = DeserializeStream<EvaluationFormDataContract>(actionContext.Request.Content.ReadAsStreamAsync().Result); } private T DeserializeStream<T>(Stream stream) { var binaryFormatter = new BinaryFormatter(); var rez = binaryFormatter.Deserialize(stream); var t = (T)binaryFormatter.Deserialize(stream); return t; }
When this code gets executed I get this exception when the binaryFormatter tryes to deserialize it:
The input stream is not a valid binary format. The starting contents (in bytes) are: 73-74-75-64-65-6E-74-41-73-73-69-67-6E-6D-65-6E-74 ...
What am I doing wrong?
解决方案You are trying to use
BinaryFormatter
to binary deserialize data which was not binary serialized. From data you sent I see that hex code represents a string.
73-74-75-64-65-6E-74-41-73-73-69-67-6E-6D-65-6E-74
decoded isstudentAssignment
This leads me to believe you are doing a simple AJAX call and sending JSON data to WebAPI service.
You need to deserialize the stream using JSON.
- Read request content as string
- If content is JSON, deserialize it using JSON.NET
var json = actionContext.Request.Content.ReadAsStringAsync().Result; var m = JsonConvert.DeserializeObject<EvaluationFormDataContract>(json);
If response is not JSON, but form data you can parse it like a query string.
var stringData = actionContext.Request.Content.ReadAsStringAsync().Result; NameValueCollection data = HttpUtility.ParseQueryString(stringData); string personId = data["personId"];
这篇关于反序列化HTTP POST内的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!