C#开发的WebService使用JSON格式传递数据+Ajax测试

[C#]  WebService 使用 JSON 格式傳遞筆記 + JQuery 測試

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 [C#] Web Service 移除 xmlns 0 2 我先移除xml namespace

再來一個重點,在每一個Method 上方我都會加上

0 2

0 2

[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]

因為基於有時候我會需要使用GET 方式傳遞 所以我在Web Config 中加入

在system.web 中加入

0 2

<webServices>
<protocols>
<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
  http://go.microsoft.com/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>
  </system.web>

  <applicationSettings>
    <JsonServiceSample.Properties.Settings>
      <setting name="JsonServiceSample_JTestService_Service1" serializeAs="String">
        <value>http://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:        
  23: 0 2 
  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 這東西必須得處理..

所以我參考這一篇 : http://encosia.com/never-worry-about-asp-net-ajaxs-d-again/

進行改寫..實測過上面三種不同的回傳值..都 OK~~

0 2

這樣對於傳統的 WebService Reference 呼叫 0 2 WebService 不會有影響..

也可以透過JQuery 呼叫傳遞透過JSON

筆記一下..給需要的人…

时间: 2024-08-27 06:41:33

C#开发的WebService使用JSON格式传递数据+Ajax测试的相关文章

WebService返回json格式数据供苹果或者安卓程序调用

1.新建一个WebService. 2. 1 /// <summary> 2 /// DemoToJson 的摘要说明 3 /// </summary> 4 [WebService(Namespace = "http://tempuri.org/",Description=("<br><p >西安xx公司</p>技术支持:王光旭"))] 5 [WebServiceBinding(ConformsTo = W

WebService 返回json格式和返回xml格式的数据

返回json格式 //using System.Web.Script.Services; [WebMethod] [ScriptMethod(UseHttpGet = true, ResponseFormat = ResponseFormat.Json)] public void HelloWorld() { Context.Response.Clear(); Context.Response.ContentType = "application/json"; Model.User.U

Android Volley获取json格式的数据

为了让Android能够快速地访问网络和解析通用的数据格式Google专门推出了Volley库,用于Android系统的网络传输.volley库可以方便地获取远程服务器的图片.字符串.json对象和json对象数组等.当然,java本身也有获取json对象的方法,然而为了更好地适应移动互联网,google专门为其做了特殊的优化,因而应该尽可能地使用Volley库. Volley官方文档:https://developer.android.com/training/volley/index.htm

将Array格式的数据解析成JSON格式的数据

在编程的过程中,数据的传输格式如何,会影响开发的效率和后期代码的维护, 并且现在许多的js中支持了JSON格式的数据, 比如angular.nodejs.本篇文章主要讲解Array(数组)形式数据的解析.其它格式的数据会在后续的文章中进行书写. (1)定义一个解析Array的类JSONArray. public class JSONArray { @SuppressWarnings("unchecked") public static String toJSONString(List

PHP接收JSON格式的数据

在API服务中,目前流行采用json形式来交互. 给前端调用的接口输出Json数据,这个比较简单,只需要组织好数据,用json_encode($array) 转化一下,前端就得到json格式的数据. 接收前端提交的json数据稍微复杂一点,原因是:PHP默认识别的数据类型是application/x-www.form-urlencoded标准的数据类型.因此,对型如text/xml 或者 soap 或者 application/octet-stream 和application/json格式之类

mysql模糊查询表里的json格式的数据-177

mysql里查询 json 数据 1.mysql里有个字段存储的是json格式的数据, 2.现在需要从页面传递参数到php再进行搜索匹配关键字, 3.将关键字页json_encode后,去like匹配这个字段,匹配不到 解决方案: 1.只针对中文搜索,存的数据一样是json,josn里面的中文一般是unicode编码的,将关键字编码一下. 2.在mysql里,"\" 是需要转义的.两种解决办法: a)因此使用"\\"来查询,数据依然是空.(mysql斜杆转义之后,会

Android读写JSON格式的数据之JsonWriter和JsonReader

最近的好几个月都没有搞Android编程了,逐渐的都忘却了一些东西.最近打算找一份Android的工作,要继续拾起以前的东西.公司月初搬家之后就一直没有网络,直到今日公司才有网络接入,各部门才开始办公.不说这些了,下面开始今天的正文. JSON格式的数据通常用于网络传输,尤其是在移动设备上与服务端进行数据交互.JSON与XML比较有明显的优势.XML格式的数据非常臃肿,传递少量的数据就要附带很多额外的格式数据.而JSON除了少量的符号外,全部是真正的数据,所以有越来越多的程序用JSON来取代XM

SQLyog-直接导出JSON格式的数据

      前言:以前做过的一个项目,有这样的一个需求使用搜索引擎来查询对应的区域信息,不过区域信息要先导出来,并且数据格式是JSON格式的,在程序中能实现这个需求,不过下面的这种方法更加的简单,通过SQL+SQLyog工具的特点直接将区域信息以JSON格式的形式导出来! 1:区域表的结构信息 2:区域关系表的结构信息 3:这个SQL语句是本次博文的核心,就是用他来拼出JSON格式的数据的,当然,仔细的看一下的话也比较简单,只是这种思路值得小记一笔 SELECT '{"regionId"

ASP.NET API(MVC) 对APP接口(Json格式)接收数据与返回数据的统一管理

话不多说,直接进入主题. 需求:基于Http请求接收Json格式数据,返回Json格式的数据. 整理:对接收的数据与返回数据进行统一的封装整理,方便处理接收与返回数据,并对数据进行验证,通过C#的特性对token进行验证,并通过时间戳的方式统一处理接收与返回的时间格式. 请求Json格式: { "Cmd": "login", "Token": "", "PageNo": 0, "OnePageNu