【问题标题】:change or disable default json serialization on an asp.net webform更改或禁用 asp.net 网络表单上的默认 json 序列化
【发布时间】:2023-04-07 09:59:01
【问题描述】:

如何防止在 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.SerializeObject(field1);        
}

输出是:

{"d":"{\"Alessio\":\"ciao\"}"}

应该是

{"d":"{ "Alessio ": "ciao"}"}

因为已经应用了两次序列化(来自 JsonConvert.SerializeObject 和默认序列化器)

有没有办法: - 禁用单个 webmethod 的默认序列化? 要么 - 仅在页面或方法上使用 Json.Net 序列化程序更改默认序列化程序? 要么 - 使用 Json.Net 全局更改默认序列化程序?

该项目是一个 webform 应用程序(不是 api 或 mvc 应用程序),不打算在 WCF 或 HttpHandler 上移动 WebMethods

【问题讨论】:

  • 您想要的输出不是有效的 JSON。你的意思是{"d": { "Alessio": "ciao" } } 吗?

标签: c# asp.net serialization json.net pagemethods


【解决方案1】:

我做了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();
}

【讨论】:

  • 这是我所知道的为 page 和 asmx 方法覆盖默认序列化程序的唯一方法。
猜你喜欢
  • 2016-02-25
  • 1970-01-01
  • 1970-01-01
  • 2023-01-30
  • 2014-08-12
  • 1970-01-01
  • 2013-01-13
相关资源
最近更新 更多