C#开发的WebService使⽤JSON格式传递数据+Ajax测试
0 2
因為⼀些因素,必須改寫WebService,很傳統,但是很多公司還在⽤..
因為XML 的關係,不想讓他傳遞資料的時候過度肥⼤,所以我必須要盡量乾淨的JSON..
於是開始我的改寫旅程..
0 2
⾸先,網路上好多好多好多⽂件,可能因為狀況不同,測試過許多也讓我搞混很多次..
最後有到答案..筆記⼀下..
0 2
⾸先我開了三個不同的WebMethod 來測試三種不同的輸出..
0 2
GetUserInfoString –取得字串
GetOneUserInfo - 取得⼀個物件
GetUsers - 取得物件們
0 2
using System.Collections.Generic;
using System.Web.Script.Services;
using System.Web.Services;
namespace JsonServiceSample
{
public class User
{
public string Name { get; set; }
public int Age { get; set; }
}
[WebService(Namespace = "", Description = "For Donma Test")]
[System.ComponentModel.ToolboxItem(false)]
[ScriptService]
public class Service1 : WebService
{
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public string GetUserInfoString(string name, int age)
{
return name + "," + age;
}
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public User GetOneUserInfo(string name, int age)
{
return (new User { Name = name, Age = age });
}
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public User[] GetUsers(string name, int age)
{
List<User> res = new List<User>();
res.Add(new User { Name = name + "1", Age = age });
res.Add(new User { Name = name + "2", Age = age });
return res.ToArray();
}
}
}
0 2
如這篇 0 2 0 2 我先移除xml namespace
再來⼀個重點,在每⼀個Method 上⽅我都會加上
0 2
0 2
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
因為基於有時候我會需要使⽤GET ⽅式傳遞所以我在Web Config 中加⼊
在system.web 中加⼊
0 2
<webServices>
<add name="HttpGet"/>
<add  name="HttpPost" />
<add name="Documentation" />
</protocols>
</webServices>
0 2
Web.Config 全⽂:
0 2
<?xml version="1.0"?>
<!--
For more information on how to configure your ASP.NET application, please visit
go.microsoft/fwlink/?LinkId=169433
-->
<configuration>
<configSections>
<sectionGroup name="applicationSettings" type="System.Configuration.ApplicationSettingsGroup, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" >
<section name="JsonServiceSample.Properties.Settings" type="System.Configuration.ClientSettingsSection, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false"    </sectionGroup>
</configSections>
<system.web>
<compilation debug="true" targetFramework="4.0" />
<httpHandlers>
</httpHandlers>
<webServices>
<protocols>
<add name="HttpGet"/>
<add  name="HttpPost" />
<add name="Documentation" />
</protocols>
</webServices>ajax实例 文件浏览
</system.web>
<applicationSettings>
<JsonServiceSample.Properties.Settings>
<setting name="JsonServiceSample_JTestService_Service1" serializeAs="String">
<value>localhost:5403/Service1.asmx</value>
</setting>
</JsonServiceSample.Properties.Settings>
</applicationSettings>
</configuration>
0 2
這樣試跑⼀下
0 2
0 2
奇怪為什麼不是JSON ,別緊張…我們繼續使⽤ JQuery 來呼叫看看..
0 2
JQuery Code :
0 2
0 2
<input type="button" id="ipt1" value="test" />
<script type="text/javascript">
1: 0 2
2:        function GetInfo() {
3:            var $res;
4:            $.ajax({
5:                type: "POST",
6:                url: "Service1.asmx/GetOneUserInfo",
7:                contentType: "application/json; charset=utf-8",
8:                async: false,
9:                cache: false,
10:                dataType: 'json',
11:                data: "{name:'當⿇',age:29}",
12:                success: function (data) {
13:                    if (data.hasOwnProperty("d")) {
14:                        $res = data.d;
15:                    }
16:                    else
17:                        $res = data;
18:                }
19:            });
20:            return $res;
21:        }
22:
24:        $('#ipt1').click(function () {
25:            var res = GetInfo();
26:            alert(res.Name);
27:        });
28:
29:
</script>
按鈕按下去之後我讓他呼叫 GetOneUserInfo 這 method
並且使⽤POST
看下結果..
0 2
0 2
恩恩..的確是JSON,但是多了⼀個 d 0 2 跟 __type 基本上 0 2 __type 不要去動他是不影響,但是 0 2 d 這東西必須得處理..所以我參考這⼀篇 :
進⾏改寫..實測過上⾯三種不同的回傳值..都 OK~~
0 2
這樣對於傳統的 WebService Reference 呼叫 0 2 WebService 不會有影響..
也可以透過JQuery 呼叫傳遞透過JSON…
筆記⼀下..給需要的⼈…