有没有办法让在VS 2005中创建的ASMX Web服务来接收和返回JSON? [英] Is there a way to get an ASMX Web Service created in VS 2005 to receive and return JSON?

查看:234
本文介绍了有没有办法让在VS 2005中创建的ASMX Web服务来接收和返回JSON?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用.NET 2.0和Visual Studio 2005来尝试创建一个可以食用既作为SOAP / XML和JSON的Web服务。我读<一href="http://stackoverflow.com/questions/288850/how-to-return-json-from-a-2-0-asmx-web-service/289332#289332">Dave沃德的回答的问题如何从2.0 ASMX Web服务返回JSON(除在 Encosia.com 阅读其他文章),但我想不通我需要怎么设置我的ASMX文件的code,以便与使用jQuery JSON工作。

两个问题:

  • 我在.NET 2.0 ASMX文件如何启用JSON?
  • 什么是简单的jQuery呼叫,可以使用JSON消费服务

另外,我注意到,自从我使用.NET 2.0,我我不能够实施使用System.Web.Script.Services.ScriptService


下面是我的C#$ C $下的演示ASMX服务:

 使用系统;
使用的System.Web;
System.Collections中使用;
使用System.Web.Services;
使用System.Web.Services.Protocols;


///&LT;总结&gt;
///摘要说明股票报价
///&LT; /总结&gt;
[WebService的(命名空间=htt​​p://tempuri.org/)]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)
公共类股票报价:System.Web.Services.WebService {

    公共股票报价(){

        //取消注释以下行,如果使用设计的组件
        //的InitializeComponent();

    }

    [WebMethod的]
    公共十进制GetStockQuote(串股票)
    {
        //这里进行数据库查询
        返回8;
    }

    [WebMethod的]
    公共字符串的HelloWorld(){
        返回的Hello World;
    }
}
 

下面是jQuery的一个片段,我发现在互联网上,并试图修改:

  $(文件)。就绪(函数(){
        $(#btnSubmit按钮)。点击(函数(事件){
            $阿贾克斯({
                键入:POST,
                的contentType:应用/ JSON的;字符集= UTF-8,
                网址:HTTP://bmccorm-xp/WebServices/HelloWorld.asmx
                数据: ,
                数据类型:JSON
            })
            。事件preventDefault();
        });
    });
 

解决方案

闻听此事与Visual Studio 2005的工作和.NET 2.0可以是一个有点棘手,特别是因为很多在互联网上引用.NET 3.5的信息,其中包括AJAX组件在默认情况下。由于 Aaonaught 提到的,您首先需要安装<一href="http://www.microsoft.com/downloads/details.aspx?FamilyID=ca9d90fa-e8c9-42e3-aa19-08e2c027f5d6&displaylang=en"相对=nofollow> ASP.NET AJAX扩展的.NET 2.0 。

安装了AJAX的扩展之后,你要添加一个新的支持AJAX网站:进入文件>新建> Web站点。选择ASP.NET AJAX的网站。这比在.NET 2.0中的常规ASP.NET网站不同的配置文件,所以要选择这样的网站,它是非常重要的。

接下来,如果它不是已经在你的网络配置中引用,你需要在你的项目中单击鼠标右键,进入添加引用。添加引用 System.Web.Extensions程序 1.0.61025.0版本。这是在新的脚本库生活(的更新:我可以证实,如果你设置了一个项目,在VS 2005作为支持AJAX的Web站点,它会自动包括提及本次大会在格兰的Web.Config文件的)。

最后两步将允许您添加的引用 System.Web.Script.Services.ScriptService 在code。现在,您可以添加的.asmx Web服务项目和所有你需要做的是服务类前添加以下属性: [System.Web.Script.Services.ScriptService] 。您的code应类似于此:

 使用系统;
使用的System.Web;
System.Collections中使用;
使用System.Web.Services;
使用System.Web.Services.Protocols;



///&LT;总结&gt;
///摘要说明股票报价
///&LT; /总结&gt;
[WebService的(命名空间=htt​​p://tempuri.org/)]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)
[System.Web.Script.Services.ScriptService]
公共类股票报价:System.Web.Services.WebService {

    公共股票报价(){

        //取消注释以下行,如果使用设计的组件
        //的InitializeComponent();

    }

    [WebMethod的]
    公共十进制GetStockQuote(串股票)
    {
        //这里进行数据库查询
        返回8;
    }

    [WebMethod的]
    公共字符串的HelloWorld(){
        返回的Hello World;
    }

}
 

你的问题,你的榜样code的一部分是,你没叫你在你的例子定义了同一个Web服务。你有一个名为 HelloWorld.asmx 从jQuery的,但你应该叫 StockQuote.asmx /的HelloWorld 。现在,当你使用打电话给你的jQuery的方法应用程序/ JSON 作为内容类型,web服务将遵守和JSON,而不是XML响应。


JSON 发表

  POST HTTP://bmccorm-xp/WebServicesAjax/StockQuote.asmx/HelloWorld HTTP / 1.1
的x要求,具有:XMLHtt prequest
接受语言:EN-US
引用站点:HTTP://bmccorm-xp/WebServicesAjax/TestJSON.html
接受:应用/ JSON,文字/ javascript中,* / *
内容类型:应用程序/ JSON;字符集= UTF-8
接受编码:gzip,紧缩
用户代理:Mozilla的/ 4.0(兼容; MSIE 7.0; Windows NT的5.1;三叉戟/ 4.0; .NET CLR 1.0.3705; .NET CLR 2.0.50727; .NET CLR 1.1.4322; .NET CLR 3.0.04506.30。 NET CLR 3.0.04506.648; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729)
主持人:bmccorm-XP
内容长度:0
连接:保持活动
杂注:无缓存
 

JSON 响应

  HTTP / 1.1 200 OK
服务器:Microsoft-IIS / 5.1
日期:星期二,2010 19点11分40秒格林尼治标准​​时间4月27日
的X已启动方式:ASP.NET
的X ASPNET-版本:2.0.50727
缓存控制:私人,最大年龄= 0
内容类型:应用程序/ JSON;字符集= UTF-8
内容长度:13

你好,世界
 


jQuery的发表,请求XML:

  POST HTTP://bmccorm-xp/WebServicesAjax/StockQuote.asmx/HelloWorld HTTP / 1.1
的x要求,具有:XMLHtt prequest
接受语言:EN-US
引用站点:HTTP://bmccorm-xp/WebServicesAjax/TestJSON.html
接受:应用/ JSON,文字/ javascript中,* / *
内容类型:text / xml的;字符集= UTF-8
接受编码:gzip,紧缩
用户代理:Mozilla的/ 4.0(兼容; MSIE 7.0; Windows NT的5.1;三叉戟/ 4.0; .NET CLR 1.0.3705; .NET CLR 2.0.50727; .NET CLR 1.1.4322; .NET CLR 3.0.04506.30。 NET CLR 3.0.04506.648; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729)
主持人:bmccorm-XP
内容长度:0
连接:保持活动
杂注:无缓存
 

XML的响应

  HTTP / 1.1 200 OK
服务器:Microsoft-IIS / 5.1
日期:星期二,2010 18时54分55秒格林尼治标准​​时间4月27日
的X已启动方式:ASP.NET
的X ASPNET-版本:2.0.50727
缓存控制:私人,最大年龄= 0
内容类型:text / xml的;字符集= UTF-8
内容长度:96

&LT; XML版本=1.0编码=UTF-8&GT?;
&LT;字符串的xmlns =htt​​p://tempuri.org/&GT;的Hello World&LT; /串&GT;
 

I'm using .NET 2.0 and Visual Studio 2005 to try to create a web service that can be consumed both as SOAP/XML and JSON. I read Dave Ward's Answer to the question How to return JSON from a 2.0 asmx web service (in addition to reading other articles at Encosia.com), but I can't figure out how I need to set up the code of my asmx file in order to work with JSON using jQuery.

Two Questions:

  • How do I enable JSON in my .NET 2.0 ASMX file?
  • What's a simple jQuery call that could consume the service using JSON?

Also, I notice that since I'm using .NET 2.0, I i'm not able to implement using System.Web.Script.Services.ScriptService.


Here's my C# code for the demo ASMX service:

using System;
using System.Web;
using System.Collections;
using System.Web.Services;
using System.Web.Services.Protocols;


/// <summary>
/// Summary description for StockQuote
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
public class StockQuote : System.Web.Services.WebService {

    public StockQuote () {

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

    }

    [WebMethod]
    public decimal GetStockQuote(string ticker)
    {
        //perform database lookup here
        return 8;
    }

    [WebMethod]
    public string HelloWorld() {
        return "Hello World";
    }        
}

Here's a snippet of jQuery I found on the internet and tried to modify:

    $(document).ready(function(){
        $("#btnSubmit").click(function(event){
            $.ajax({
                type: "POST",
                contentType: "application/json; charset=utf-8",
                url: "http://bmccorm-xp/WebServices/HelloWorld.asmx",
                data: "",
                dataType: "json"
            })
            event.preventDefault();
        });
    });

解决方案

Getting this to work with Visual Studio 2005 and .NET 2.0 can be a little tricky, especially since a lot of the information on the internet references .NET 3.5, which included the AJAX components by default. As Aaonaught mentioned, you'll first need to install the ASP.NET AJAX Extensions for .NET 2.0.

After the AJAX extensions are installed, you'll want to add a new "AJAX Enabled" website: Go to File > New > Web Site. Choose "ASP.NET AJAX Enabled Website." This will have a different config file than the regular ASP.NET site in .NET 2.0, so it's important to choose this kind of site.

Next, if it's not already referenced in your web config, you'll need to right-click on your project and go to "Add Reference." Add a reference to System.Web.Extensions version 1.0.61025.0. This is where the new scripting libraries live (UPDATE: I can confirm that if you set up a project in VS 2005 as an "AJAX Enabled Web Site", it will automatically include a reference to this assembly in teh Web.Config file).

The last two steps will allow you to add a reference to System.Web.Script.Services.ScriptService in your code. Now you can add an .asmx web service to your project and all you need to do is add the following attribute before your service class: [System.Web.Script.Services.ScriptService]. Your code should look similar to this:

using System;
using System.Web;
using System.Collections;
using System.Web.Services;
using System.Web.Services.Protocols;



/// <summary>
/// Summary description for StockQuote
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.Web.Script.Services.ScriptService]
public class StockQuote : System.Web.Services.WebService {

    public StockQuote () {

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

    }

    [WebMethod]
    public decimal GetStockQuote(string ticker)
    {
        //perform database lookup here
        return 8;
    }

    [WebMethod]
    public string HelloWorld() {
        return "Hello World";
    }

}

Part of your problem with your example code is that you didn't call the same web service that you had defined in your example. You had called HelloWorld.asmx from jQuery, but you should have called StockQuote.asmx/HelloWorld. Now when you call your jQuery method using application/json as the content type, the webservice will obey and respond with JSON instead of XML.


JSON POST

POST http://bmccorm-xp/WebServicesAjax/StockQuote.asmx/HelloWorld HTTP/1.1
x-requested-with: XMLHttpRequest
Accept-Language: en-us
Referer: http://bmccorm-xp/WebServicesAjax/TestJSON.html
Accept: application/json, text/javascript, */*
Content-Type: application/json; charset=utf-8
Accept-Encoding: gzip, deflate
User-Agent: Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; Trident/4.0; .NET CLR 1.0.3705; .NET CLR 2.0.50727; .NET CLR 1.1.4322; .NET CLR 3.0.04506.30; .NET CLR 3.0.04506.648; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729)
Host: bmccorm-xp
Content-Length: 0
Connection: Keep-Alive
Pragma: no-cache

JSON Response:

HTTP/1.1 200 OK
Server: Microsoft-IIS/5.1
Date: Tue, 27 Apr 2010 19:11:40 GMT
X-Powered-By: ASP.NET
X-AspNet-Version: 2.0.50727
Cache-Control: private, max-age=0
Content-Type: application/json; charset=utf-8
Content-Length: 13

"Hello World"


jQuery POST, asking for XML:

POST http://bmccorm-xp/WebServicesAjax/StockQuote.asmx/HelloWorld HTTP/1.1
x-requested-with: XMLHttpRequest
Accept-Language: en-us
Referer: http://bmccorm-xp/WebServicesAjax/TestJSON.html
Accept: application/json, text/javascript, */*
Content-Type: text/xml; charset=utf-8
Accept-Encoding: gzip, deflate
User-Agent: Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; Trident/4.0; .NET CLR 1.0.3705; .NET CLR 2.0.50727; .NET CLR 1.1.4322; .NET CLR 3.0.04506.30; .NET CLR 3.0.04506.648; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729)
Host: bmccorm-xp
Content-Length: 0
Connection: Keep-Alive
Pragma: no-cache

XML Response:

HTTP/1.1 200 OK
Server: Microsoft-IIS/5.1
Date: Tue, 27 Apr 2010 18:54:55 GMT
X-Powered-By: ASP.NET
X-AspNet-Version: 2.0.50727
Cache-Control: private, max-age=0
Content-Type: text/xml; charset=utf-8
Content-Length: 96

<?xml version="1.0" encoding="utf-8"?>
<string xmlns="http://tempuri.org/">Hello World</string>

这篇关于有没有办法让在VS 2005中创建的ASMX Web服务来接收和返回JSON?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆