C# 更改或禁用asp.net Web表单上的默认json序列化
如何防止aspnet webform web方法(而不是api或mvc)中的默认序列化,以使用Json.netC# 更改或禁用asp.net Web表单上的默认json序列化,c#,asp.net,serialization,json.net,pagemethods,C#,Asp.net,Serialization,Json.net,Pagemethods,如何防止aspnet webform web方法(而不是api或mvc)中的默认序列化,以使用Json.net using Newtonsoft.Json.Linq; using Newtonsoft.Json; [WebMethod] public static object MyMethod() { dynamic field1 = new JObject(); field1.Alessio = "ciao"; return JsonConvert.Ser
using Newtonsoft.Json.Linq;
using Newtonsoft.Json;
[WebMethod]
public static object MyMethod()
{
dynamic field1 = new JObject();
field1.Alessio = "ciao";
return JsonConvert.SerializeObject(field1);
}
输出为:
{"d":"{\"Alessio\":\"ciao\"}"}
应该是这样
{"d":"{ "Alessio ": "ciao"}"}
因为序列化应用了两次(从JsonConvert.SerializeObject和从默认序列化程序)
有没有办法:
-是否禁用单个webmethod的默认序列化?
或
-是否仅在页面或方法上使用Json.Net serializar更改默认序列化程序?
或
-是否全局更改Json.Net的默认序列化程序
该项目是一个webform应用程序(不是api或mvc应用程序),不打算在WCF或HttpHandler上移动WebMethodsI使webmethod“void
”(以防止自动序列化)
并通过手动/手工创建响应来设置正确的http头:
[WebMethod]
public static void MyMethod()
{
.....
...
..
string result = JsonConvert.SerializeObject(_d);
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.ContentType = "application/json";
HttpContext.Current.Response.AddHeader("content-length", result.Length.ToString()); HttpContext.Current.Response.Flush();
HttpContext.Current.Response.Write(result);
HttpContext.Current.ApplicationInstance.CompleteRequest();
}
所需的输出不是有效的JSON。你的意思是
{“d”:{“alesio”:“ciao”}
吗?这是我所知道的覆盖page和asmx方法的默认序列化程序的唯一方法。