如何让 ASMX 文件输出 JSON

发布于 2024-07-07 02:40:16 字数 426 浏览 4 评论 0原文

我创建了一个带有代码隐藏文件的 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" };
    }
}

I created an ASMX file with a code behind file. It's working fine, but it is outputting XML.

However, I need it to output JSON. The ResponseFormat configuration doesn't seem to work. My code-behind is:

[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" };
    }
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

德意的啸 2024-07-14 02:40:17

要接收纯 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}");
        }
    }

To receive a pure JSON string, without it being wrapped into an XML, you have to write the JSON string directly to the HttpResponse and change the WebMethod return type to void.

    [System.Web.Script.Services.ScriptService]
    public class WebServiceClass : System.Web.Services.WebService {
        [WebMethod]
        public void WebMethodName()
        {
            HttpContext.Current.Response.Write("{property: value}");
        }
    }
暗藏城府 2024-07-14 02:40:17

来自 即使 ResponseFormat 设置为 JSON,WebService 也会返回 XML

确保请求是 POST 请求,而不是 GET。 斯科特·格思里 (Scott Guthrie) 有一个 帖子解释原因

虽然它是专门为 jQuery 编写的,但这可能对您也有用:
使用jQuery 使用 ASP.NET JSON Web 服务

From WebService returns XML even when ResponseFormat set to JSON:

Make sure that the request is a POST request, not a GET. Scott Guthrie has a post explaining why.

Though it's written specifically for jQuery, this may also be useful to you:
Using jQuery to Consume ASP.NET JSON Web Services

昔梦 2024-07-14 02:40:17

现在这可能是旧新闻了,但神奇之处似乎在于:

  • Web 服务类上的 [ScriptService] 属性
  • [ScriptMethod(UseHttpGet = true, ResponseFormat = ResponseFormat.Json)] 方法
  • Content-type: application/json in request

与那些件就位,GET 请求成功。

对于方法和客户端上的 HTTP POST

  • [ScriptMethod(UseHttpGet = false, ResponseFormat = ResponseFormat.Json)]

(假设您的 Webmethod 名为 MethodName,并且它采用名为 searchString 的单个参数):

        $.ajax({
            url: "MyWebService.asmx/MethodName",
            type: "POST",
            contentType: "application/json",
            data: JSON.stringify({ searchString: q }),
            success: function (response) {                  
            },
            error: function (jqXHR, textStatus, errorThrown) {
                alert(textStatus + ": " + jqXHR.responseText);
            }
        });

This is probably old news by now, but the magic seems to be:

  • [ScriptService] attribute on web service class
  • [ScriptMethod(UseHttpGet = true, ResponseFormat = ResponseFormat.Json)] on method
  • Content-type: application/json in request

With those pieces in place, a GET request is successful.

For a HTTP POST

  • [ScriptMethod(UseHttpGet = false, ResponseFormat = ResponseFormat.Json)] on method

and on the client side (assuming your webmethod is called MethodName, and it takes a single parameter called searchString):

        $.ajax({
            url: "MyWebService.asmx/MethodName",
            type: "POST",
            contentType: "application/json",
            data: JSON.stringify({ searchString: q }),
            success: function (response) {                  
            },
            error: function (jqXHR, textStatus, errorThrown) {
                alert(textStatus + ": " + jqXHR.responseText);
            }
        });
黑寡妇 2024-07-14 02:40:17

我通过艰难的方式学到了一个快速问题(基本上在 Google 上花费了 4 个小时),您可以在 ASPX 文件中使用 PageMethods 为静态方法返回 JSON(带有 [ScriptMethod()] 标记),但是如果您决定移动将静态方法添加到 asmx 文件中,它不能是静态方法。

另外,您需要告诉 Web 服务 Content-Type: application/json 以便从调用中获取 JSON(我使用 jQuery 和 使用 jQuery 时要避免的 3 个错误 文章非常有启发性 - 它来自同一个网站在另一个答案中提到)。

A quick gotcha that I learned the hard way (basically spending 4 hours on Google), you can use PageMethods in your ASPX file to return JSON (with the [ScriptMethod()] marker) for a static method, however if you decide to move your static methods to an asmx file, it cannot be a static method.

Also, you need to tell the web service Content-Type: application/json in order to get JSON back from the call (I'm using jQuery and the 3 Mistakes To Avoid When Using jQuery article was very enlightening - its from the same website mentioned in another answer here).

兔小萌 2024-07-14 02:40:17

您是从客户端脚本还是在服务器端调用 Web 服务?

您可能会发现向服务器发送内容类型标头会有所帮助,例如

“application/json;” charset=utf-8'

在客户端,我使用原型客户端库,并且在进行 Ajax 调用时有一个 contentType 参数,您可以在其中指定它。 我认为 jQuery 有一个 getJSON 方法。

Are you calling the web service from client script or on the server side?

You may find sending a content type header to the server will help, e.g.

'application/json; charset=utf-8'

On the client side, I use prototype client side library and there is a contentType parameter when making an Ajax call where you can specify this. I think jQuery has a getJSON method.

不打扰别人 2024-07-14 02:40:17

替代方案:使用通用 HTTP 处理程序 (.ashx) 并使用您最喜欢的 json 库手动序列化和反序列化您的 JSON。

我发现对请求处理和生成响应的完全控制胜过 .NET 为简单、RESTful Web 服务提供的任何其他功能。

Alternative: Use a generic HTTP handler (.ashx) and use your favorite json library to manually serialize and deserialize your JSON.

I've found that complete control over the handling of a request and generating a response beats anything else .NET offers for simple, RESTful web services.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文