本文介绍了C#Web服务将不输出JSON,仅输出XML的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将jQuery和JSON与我编写的C#Web服务结合使用.无论如何,以下代码将仅以XML输出.

I'm trying to use jQuery and JSON with a C# Web Service that I wrote. No matter what, the following code will only output in XML.

网络服务代码

[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public string HelloWorld() {
    return "Hello World!";
}

我也将这些属性分配给了班级

I also have these attributes assigned to the class

[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[ScriptService]

jQuery代码

$.ajax({
    type: "POST",
    contentType: "application/json; charset=utf-8",
    url: "ScheduleComputerDS.asmx/HelloWorld",
    data: "{}",
    dataType: "jsonp",
    success: function(data) {
        alert(data);
    }
});

ASMX页面始终以内容类型"text/xml"返回.我有什么想念吗?

The ASMX page always returns as content type "text/xml". Anything I'm missing?

编辑:针对几个答案:

如果我的数据类型只是"json",则内容仍然是XML,而jQuery也不会调用我的回调函数.如果我添加& callback =?"网址时,IIS会引发HTTP 500错误.

If I have the datatype as just "json" the content is still XML and jQuery also will not call my callback function. If I add the "&callback=?" to the url, IIS throws a HTTP 500 error.

我的课程确实从"System.Web.Services.WebService"继承.

My class does inherit from "System.Web.Services.WebService".

通过对你们的答案进行一些研究,看来我确实需要弄乱WCF.不幸的是,返回的JSON是为MS Ajax设计的,对于我的使用来说是很多无用的东西.我可能会研究像Jayrock之类的开源库.

From doing some research on your guys answers, it looks like I do need to mess with WCF. Unfortunately the JSON that is returned is more designed for MS Ajax and is a lot of useless bloat for my use. I may look into an open source library like Jayrock or something similar.

感谢您的所有帮助!

推荐答案

据我所知,ScriptService属性仅允许服务自动创建JavaScript代理(通过将/js附加到端点地址-ScheduleComputerDS.asmx/js).它不允许您以尝试的方式调用服务上的操作.

As far as I know, the ScriptService attribute just allows the service to automatically create a JavaScript proxy (by appending /js to the endpoint address - ScheduleComputerDS.asmx/js in your case). It does not allow you to call the operations on the service the way you're trying to do.

您可以改为使用RESTful WCF服务(需要.NET 3.5),您可以通过通过HTTP GET发送适当形状的URI来访问该服务.

You could instead use a RESTful WCF service (which requires .NET 3.5) which you can access by sending a properly shaped URI via an HTTP GET.

这篇关于C#Web服务将不输出JSON,仅输出XML的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-23 22:40