C# WebService输出JSON 实现二

一般js请求web服务uk可以通过 contentType: "application/json"  获取json效果,为了取得更好的效果,可以在服务端强制返回JSON格式

服务端代码(c#)

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;
using Newtonsoft.Json;

namespace ajaxjson
{
    /// <summary>
    /// demo 的摘要说明
    /// </summary>
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]
    // 若要允许使用 ASP.NET AJAX 从脚本中调用此 Web 服务,请取消注释以下行。 
   [System.Web.Script.Services.ScriptService]
    public class demo : System.Web.Services.WebService
    {

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

        [WebMethod]
        public void  Login(string username,string password)
        {
            User u=new User();
            u.name = "demo";
            u.username = username;
            u.password = password;
            u.money = 1.00;
            string json = JsonConvert.SerializeObject(u);
            Context.Response.Write(json);
            Context.Response.End();
        }
        [WebMethod]
        public void GetUser(int id)
        {
            User u = new User();
            u.name = "demo";
            u.username = "ddd";
            u.password = "333";
            u.money = 1.00;
            string json = JsonConvert.SerializeObject(u);
            Context.Response.Write(json);
            Context.Response.End();
        }

        [WebMethod]
        public void GetList()
        {
            List<User> list=new List<User>();
            User u = new User();
            u.name = "demo";
            u.username = "123";
            u.password = "456";
            u.money = 1.00;
            list.Add(u);
            
            u = new User();
            u.name = "demo";
            u.username = "4444";
            u.password = "6666";
            list.Add(u);
            //该处理会导致必须使用json处理
            string json = JsonConvert.SerializeObject(list);
            Context.Response.Write(json);
            Context.Response.End();
        }
    }

    public class User
    {
        public string username { get; set; }
        public string password { get; set; }
        public string name { get; set; }
        public double money { get; set; }
    }
}
View Code

客户端代码

jQuery.ajax( {  
    url:'http://127.0.0.1:81/demo.asmx/Login',
    data:{
    	username:"123456",
    	password:"123456"
    },   
    type:'post',   
    dataType:'json',      
    success:function(data) { 
    		 //===========
      
     },  
     error : function(xhr,status,error) { 
        //===========
     }  
  });

  

 补充AJAX跨域问题:

由于JSONP get的限制这里采用XHR2的CORS的模式,即利用Headers中的Origin参数实现,这里直接在配置文件中设置,留意红色部分

<?xml version="1.0"?>
<configuration>
  <system.web>
    <compilation debug="true" targetFramework="4.0"/>
    <httpRuntime/>
      <webServices>
          <protocols>
              <add name="HttpSoap"/>
              <add name="HttpPost"/>
              <add name="HttpGet"/>
          </protocols>
      </webServices>
  </system.web>
  <system.webServer>
    <httpProtocol>
      <customHeaders>
        <add name="Access-Control-Allow-Methods" value="OPTIONS,POST,GET"/>
        <add name="Access-Control-Allow-Headers" value="Origin,X-Requested-With,Content-Type,Accept" />
        <add name="Access-Control-Allow-Origin" value="*"/>
      </customHeaders>
    </httpProtocol>
  </system.webServer>
    <!--配置JSON序列化-->
    <system.web.extensions>
        <scripting>
            <webServices>
                <jsonSerialization maxJsonLength="10000"/>
            </webServices>
        </scripting>
    </system.web.extensions>
</configuration>

 

  

配置后就可以使用普通的AJAX方式访问该服务了

扩展:PHP中跨域配置

header('Access-Control-Allow-Origin: *');
//header('Content-type: text/plain');

  

 

posted @ 2016-06-28 14:07  Merray  Views(11092)  Comments(0Edit  收藏  举报