C# 如何从网络服务返回 JSON

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11447538/
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-08-09 17:53:32  来源:igfitidea点击:

How to return JSON from webservice

c#asp.netjsonweb-services

提问by thatuxguy

Morning,

早晨,

I need to return a message from my web service. Below is a sample of my code, and i am returning a string.

我需要从我的网络服务返回一条消息。下面是我的代码示例,我正在返回一个字符串。

[web method]
public string CheckFeedSubmission()
    {
        string responseText = "";
        try
        {
            //Stuff goes here
            responseText = "It Worked!"
        }
        catch (Exception ex) { responseText = "Opps wehave an error! Exception message:" + ex.Message; }
        return responseText ;
    }

I currently get the following response...

我目前收到以下回复...

<string xmlns="http://tempuri.org/"/>

I would ideally like to return something like

理想情况下,我想返回类似的东西

 {"success" : true, "message" : "***Message Here***"}

I am sure once i get the idea of it, i will be able to return other items if needed. Its just this base i need to work out.

我相信一旦我有了它的想法,如果需要,我将能够退回其他物品。这只是我需要锻炼的基础。

All help is much appreciated, thanks in advance :)

非常感谢所有帮助,提前致谢:)

UPDATE: Just found this...

更新:刚刚发现这个......

 return "{Message:'hello world'}"

Would i need something like

我需要类似的东西吗

 responseText = "{"success" : true, "message" : \"There has been an error. Message: " + ex.Message + "\"}"

采纳答案by Ashwin Singh

Use:

用:

[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]//Specify return format.
public string CheckFeedSubmission()
    {
        string responseText = "";
        try
        {
            //Stuff goes here
            responseText = "It Worked!"
        }
        catch (Exception ex) { responseText = "Opps wehave an error! Exception message:" + ex.Message; }
        return responseText ;
    }

The result returned will be like:

返回的结果将类似于:

<string xmlns="http://tempuri.org/"/>
 {"success" : true, "message" : "***Message Here***"}
</string>

回答by HatSoft

Please use the attribute for your webmethod

请为您的 webmethod 使用该属性

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

The caller will have set his contenttype to application/json to use the webmethod

调用者将他的内容类型设置为 application/json 以使用 webmethod

回答by Ravin Singh

Try this one :

试试这个:

[WebMethod] 
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]//Specify return format. 
public bool addUser(UserModel um)
    {
        bool result = false;
        result = Conversion.intToBool(SplashAwardsDB.executeNonQuery(
            "INSERT INTO dbo.User ("
            + "userName, password, firstName, lastName, address, contactNo, birthDate, familyID, familyRole, x, y ) "
            + " VALUES ("
            + "'" + um.userName + "', "
            + "'" + um.password + "', "
            + "'" + um.firstName + "', "
            + "'" + um.lastName + "', "
            + "'" + um.address + "', "
            + "'" + um.contactNo + "', "
            + "'" + um.birthDate + "', "
            + "'" + um.familyID + "', "
            + "'" + um.familyRole + "', "
            + "'" + um.x + "', "
            + "'" + um.y + "')"
            ));
        return result;
    }

回答by kalenwatermeyer

To remove the XML tags in your service response, see this answer on StackOverflow:

要删除服务响应中的 XML 标记,请参阅 StackOverflow 上的此答案:

ASP.NET WebService is Wrapping my JSON response with XML tags

ASP.NET WebService 正在用 XML 标记包装我的 JSON 响应

回答by Leonardo Mora

This my solution for the framewok 4.5.2, In the class FilterConfig add the following code, Note: you will need the lib Newtonsoft.

这是我针对 framewok 4.5.2 的解决方案,在类 FilterConfig 中添加以下代码,注意:您将需要 lib Newtonsoft。

 public class FilterConfig
{
    public static void RegisterGlobalFilters(GlobalFilterCollection filters)
    {
        GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Serialize;
        GlobalConfiguration.Configuration.Formatters.Remove(GlobalConfiguration.Configuration.Formatters.XmlFormatter);
        GlobalConfiguration.Configuration.EnableCors();
        filters.Add(new HandleErrorAttribute());
    }
}