【问题标题】:Create basic webservice for JSON response in ASP.NET在 ASP.NET 中为 JSON 响应创建基本 Web 服务
【发布时间】:2015-04-20 09:08:30
【问题描述】:

我在 ASP.NET 中创建了一个 webservice 示例。它正在生成响应 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

【问题讨论】:

标签: c# asp.net json web-services


【解决方案1】:

检查您的配置文件。大概this answer可以解决你的问题:

<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>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-09-09
    • 1970-01-01
    相关资源
    最近更新 更多