c# - 如何让 ASMX 文件输出 JSON

标签 c# json asmx

我创建了一个带有代码隐藏文件的 ASMX 文件。它工作正常,但它正在输出 XML。

但是,我需要它来输出 JSON。 ResponseFormat 配置似乎不起作用。我的代码隐藏是:

[System.Web.Script.Services.ScriptService]
public class _default : System.Web.Services.WebService {
    [WebMethod]
    [ScriptMethod(UseHttpGet = true,ResponseFormat = ResponseFormat.Json)]
    public string[] UserDetails()
    {
        return new string[] { "abc", "def" };
    }
}

最佳答案

要接收纯 JSON 字符串,而不将其包装到 XML 中,您必须将 JSON 字符串直接写入 HttpResponse 并将 WebMethod 返回类型更改为无效.

    [System.Web.Script.Services.ScriptService]
    public class WebServiceClass : System.Web.Services.WebService {
        [WebMethod]
        public void WebMethodName()
        {
            HttpContext.Current.Response.Write("{property: value}");
        }
    }

关于c# - 如何让 ASMX 文件输出 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/211348/

相关文章:

c# - 如何使用 C# 触发基于 Application Insights 消息的 Azure 函数?

c# - 具有有状态事件参数的异步事件处理程序

c# - 使用 C# 比较 2 个图像

javascript - Node js 错误 : Protocol "https:" not supported. 预期为 "http:"

asp.net - 如何将 asmx 的返回数据放入 JSON 中?

c# - 创建 Controller 时为"Exception has been thrown by target of invocation"(带有MySql的ASP.NET MVC 5)

java - java中如何修改json字符串?

c# - 在 JSON.NET 中如何获取对每个反序列化对象的引用?

c# - SoapHttpClientProtocol 线程安全吗?

asp.net - IIS 中的服务引用