簡體   English   中英

在ASP.NET中為JSON響應創建基本的Web服務

[英]Create basic webservice for JSON response in ASP.NET

我已經在ASP.NET中創建了一個Web服務示例。 它正在生成響應JSON格式,但響應使用XML標簽包裝。 我不想將XML和JSON混合輸出。

ASP.NET代碼:

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

/// <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(); 
}

[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public string TestJSON()
{
    Employee[] e = new Employee[2];

    e[0] = new Employee();
    e[0].Name = "Bhavesh";
    e[0].Company = "TCS";

    e[1] = new Employee();
    e[1].Name = "Jiten";
    e[1].Company = "Infosys";

    return new JavaScriptSerializer().Serialize(e);
 }
}

public class Employee
{
   public string Name { get; set; }
   public string Company { get; set; }
}

輸出:

This XML file does not appear to have any style information associated with it. The document tree is shown below.
<string xmlns="http://tempuri.org/">
[{"Name":"Bhavesh","Company":"TCS"},{"Name":"Jiten","Company":"Infosys"}]
</string>

注意:我不想使用jQuery或其他類似jQuery的工具。 我需要JSON中的簡單輸出。 我正在使用Visual Studio 2012

檢查您的配置文件。 此答案可能可以解決您的問題:

<configuration>
    <system.web>
        <compilation debug="true" targetFramework="4.0" />
    </system.web>
    <system.webServer>
        <handlers>
            <add name="ScriptHandlerFactory"
                 verb="*" path="*.asmx"
                 type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
                 resourceType="Unspecified" />
        </handlers>
    </system.webServer>
</configuration>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM