ASP.NET JSON Web 服务始终返回包装在 XML 中的 JSON 响应

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1121559/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 17:17:32  来源:igfitidea点击:

ASP.NET JSON web service always return the JSON response wrapped in XML

xmljsonasmx

提问by JohnnyCantCode

I saw a similar question but it did not resolve my issue. I have a JSON web service in an ASMX file;

我看到了一个类似的问题,但它没有解决我的问题。我在 ASMX 文件中有一个 JSON Web 服务;

The code for the web method

web方法的代码

        [WebMethod]
        [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
        public string GetUserRoles(string JSONUserCode)
        {
            string retRoles = string.Empty;
            List<JSONRole> roles = new List<JSONRole>();

            {... I Populate the roles here ...}

            DataContractJsonSerializer serializer = new
            DataContractJsonSerializer(roles.GetType());
            MemoryStream ms = new MemoryStream();
            serializer.WriteObject(ms, roles);
            string jsonString = Encoding.Default.GetString(ms.ToArray());
            ms.Close();
            return jsonString;
        }

This correctly formats the List correctly but wraps the entire return in XML. Here is the response:

这正确地格式化了列表,但将整个返回包装在 XML 中。这是回应:

<?xml version="1.0" encoding="utf-8" ?> 
    <string xmlns="http://formshare.com/">
       [{"Name":"Accounts Payable"},{"Name":"Payroll"}]
    </string>

You can view the Response your self by clicking this link:

您可以通过单击此链接查看自己的响应:

http://dev.formshare.gologictech.com/JSON/JSONService.asmx/GetUserRoles?JSONUserCode=1234

http://dev.formshare.gologictech.com/JSON/JSONService.asmx/GetUserRoles?JSONUserCode=1234

I need the response to be just:

我需要的回应只是:

[{"Name":"Accounts Payable"},{"Name":"Payroll"}]

Any ideas? Thanks for your help.

有任何想法吗?谢谢你的帮助。

回答by dxh

The WebMethod is able to serve the same information both as XML and JSON. You need to specify what format you want (dataType) in the client, as you submit your request.

WebMethod 能够提供与 XML 和 JSON 相同的信息。在提交请求时,您需要在客户端指定所需的格式 (dataType)。

Also, you're not supposed to serialize the object to JSON manually, but rather, return roles, and it will be serialized to JSON if your client requests the data as JSON.

此外,您不应该手动将对象序列化为 JSON,而是返回角色,如果您的客户端请求数据为 JSON,它将被序列化为 JSON。

EDIT

编辑

jQuery example (note the dataType parameter):

jQuery 示例(注意 dataType 参数):

$.ajax({
   type: 'GET',
   url: 'http://dev.formshare.gologictech.com/JSON/JSONService.asmx/GetUserRoles',
   contentType: 'application/json; charset=utf-8',
   dataType: 'json',
   data: '{"JSONUserCode":"1234"}',
   success: myCallback
});

It is worth mentioning that the object will not be returned in exactly the format you specified, but rather, wrapped in an object:

值得一提的是,该对象不会以您指定的格式返回,而是包装在一个对象中:

{ d: [ {"Name":"Accounts Payable"}, {"Name":"Payroll"} ] }

This, however, is actually quite desirable, for added security

然而,这实际上是非常可取的,以增加安全性

回答by Sebastien Binette

Turns out it's not dataType that counts but

原来重要的不是 dataType 而是

contentType: 'application/json; charset=utf-8'.  

It worked like a charm.

它就像一个魅力。

回答by Emre

I made the same mistake by handling the serialization myself. You re not supposed to return string but the object itself.

我自己处理序列化时犯了同样的错误。您不应该返回字符串,而是返回对象本身。

If you have already developed a hundred Services like this, a work around for you: just created a aspx, ServiceCaller.aspx, remove everything in the html just leave the page directive and use the codebehind to call the service and Response.Write the string. Also take the Service method name as a parameter like "HelloWorld" and use reflection to invoke it.

如果您已经开发了一百个这样的服务,那么为您解决一个问题:刚刚创建了一个 aspx,ServiceCaller.aspx,删除 html 中的所有内容,只保留页面指令并使用代码隐藏来调用服务和 Response.Write 字符串. 也可以把Service方法名作为“HelloWorld”之类的参数,使用反射来调用。

It's kinda showing your left ear with your right hand but it works. You can also easily integrate a roles management and using reflection get the service name as string check the db if the user can call this service and with reflection Invoke the method.

这有点像用右手展示你的左耳,但它有效。您还可以轻松集成角色管理并使用反射获取服务名称作为字符串检查数据库是否用户可以调用此服务并使用反射调用该方法。

(any comments on this is welcome :)

(欢迎对此提出任何意见:)

回答by Pavel Morshenyuk

Make sure your service class has [ScriptService] attribute. This attribute is not added by default.

确保您的服务类具有 [ScriptService] 属性。默认情况下不添加此属性。

回答by Ivan

Try Jayrock for .NET, it's a neat handler for .NET JSON RPC. It'll do exactly what you need. There's a step by step how-to for ASP .NET JSON RPC here.

试试 Jayrock for .NET,它是 .NET JSON RPC 的简洁处理程序。它会完全满足您的需求。这里有ASP .NET JSON RPC的分步操作方法。

回答by Devadonn

Use like this not return string type.Just write

像这样使用不返回字符串类型。只写

public void Metod()
    {
        json = jss.Serialize(Data);
        Context.Response.Write(json);
    }

回答by Emre

We have made another page that calls the service server side and writes the response (in our case an .aspx). We cleaned up all the HTML code, doctype head body, and made the server side code to call the service and response.write it.

我们制作了另一个页面来调用服务服务器端并写入响应(在我们的例子中是 .aspx)。我们清理了所有的 HTML 代码,doctype head body,并制作了服务端代码来调用服务和 response.write。

(in aspx case just leave the page directive at the top)

(在 aspx 情况下,只需将页面指令留在顶部)

this way you can get a clean string.

这样你就可以得到一个干净的字符串。

By the way if this is exposing our application to any security threats or major performance hits, I'd really appreciate the comments. Just too busy to ask it here or search on it :)

顺便说一下,如果这会使我们的应用程序面临任何安全威胁或重大性能损失,我非常感谢您的评论。只是太忙了,无法在这里提问或搜索它:)

回答by Rama Subba Reddy M

Your missed only "static" keyword in method declaration please look into the following it should work.

您在方法声明中仅遗漏了“静态”关键字,请查看以下内容,它应该可以工作。

FYI: All the web methods should be static

仅供参考:所有网络方法都应该是静态的

[WebMethod] [ScriptMethod(ResponseFormat = ResponseFormat.Json)]

[WebMethod] [ScriptMethod(ResponseFormat = ResponseFormat.Json)]

    public static string GetUserRoles(string JSONUserCode)
    {
        string retRoles = string.Empty;
        List<JSONRole> roles = new List<JSONRole>();

        {... I Populate the roles here ...}

        DataContractJsonSerializer serializer = new
        DataContractJsonSerializer(roles.GetType());
        MemoryStream ms = new MemoryStream();
        serializer.WriteObject(ms, roles);
        string jsonString = Encoding.Default.GetString(ms.ToArray());
        ms.Close();
        return jsonString;
    }

回答by JayC

Instead of returning a string in your WebMethod use:

而不是在您的 WebMethod 中返回字符串使用:

JavaScriptSerializer js = new JavaScriptSerializer();
Context.Response.Write(js.Serialize(YOUR_STRING_TO_OUTPUT));