0

这是一个生成 json 的 C# Web 服务,但它包装在 XML 中。有什么简单的方法可以在服务器端代码上解决这个问题吗?这是一个简单的网站解决方案。我的 web.config 中可能缺少某些内容吗?

非常感谢。

更新:这里的一个答案由于某种原因消失了,但这是一个很好的建议,我不序列化和重新运行 json 对象。我不知道该怎么做。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Web.Script.Serialization;

/// <summary>
/// Summary description for WebService
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. 
[System.Web.Script.Services.ScriptService]
public class WebService : System.Web.Services.WebService
{

    public WebService()
    {

        //Uncomment the following line if using designed components 
        //InitializeComponent(); 
    }

    DataClassesDataContext dc = new DataClassesDataContext();


[WebMethod]
    public string GetID(string id)
    {


        var json = "";
        var uid = from result in dc.GET_ID(id) select result;

        JavaScriptSerializer jss = new JavaScriptSerializer();

        json = jss.Serialize(uid);

        return json;
    }
4

1 回答 1

0

The deleted answer suggested first to use ScriptMethod or ScriptService attributes (i.e. [ScriptMethod(UseHttpGet = false, ResponseFormat=ResponseFormat.Json)]).

That is the correct approach to return json from a web service in .NET.

See here for more info: How to let an ASMX file output JSON.

于 2013-09-07T12:33:25.837 回答