ASP.NET互動Rest服務介面(Jquery的Get與Post方式)

來源:互聯網
上載者:User

本文將通過一個簡單的執行個體,介紹如何建立一個Rest服務介面,以及通過JQUERY去對它進行調用;主要採取兩種方式分別為Get跟Post;其中將通過Post提交簡單類型(Sring)以及複雜類型(自訂實現UserModel)與Rest服務進行互動;

一 Rest服務建立

其中Web用戶端(ClintWeb)不對其它層的引用,只通過Rest部署後的服務進行效互;

1:實體層(Model)

using System.Runtime.Serialization;namespace Model{    [DataContract]    public class UserModel    {        [DataMember]        public int ID { get; set; }        [DataMember]        public string UserName { get; set; }        [DataMember]        public string PassWord { get; set; }        [DataMember]        public int Age { get; set; }        public override string ToString()        {            return string.Format("ID:{0};姓名: {1};年齡:{2};密碼:{3}",ID, UserName, Age, PassWord);        }    }}

此處要注意[DataContract],[DataMember]在命名空間using System.Runtime.Serialization下面;

 
2:介面層(IServiceInterface)

using System.ServiceModel.Web;using System.ServiceModel;using Model;namespace IServiceInterface{    [ServiceContract]    public interface IUser    {        [WebGet(UriTemplate = "/{ID}", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)]        UserModel GetUserFromID(string ID);        [WebGet(UriTemplate = "All", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json,         BodyStyle = WebMessageBodyStyle.Bare)]        List<UserModel> GetAllUser();        [WebInvoke(UriTemplate = "/User/UserName", Method = "POST", RequestFormat = WebMessageFormat.Json,ResponseFormat=WebMessageFormat.Json,         BodyStyle = WebMessageBodyStyle.WrappedRequest)]        String GetUserName(string Name);        [WebInvoke(UriTemplate = "/User/Post", Method = "POST", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json,         BodyStyle = WebMessageBodyStyle.WrappedRequest)]        string UpdateUser(UserModel model);    }}

3:邏輯層(ServiceBll)

using IServiceInterface;using Model;namespace ServiceBll{    public class UserBll:IUser    {        public static List<UserModel> GetUserList()        {            List<UserModel> list = new List<UserModel>()            {                new UserModel(){ID=1,UserName="踏浪帥",PassWord="123456",Age=27},                new UserModel(){ID=2,UserName="wujunyang",PassWord="345678",Age=30},                new UserModel(){ID=3,UserName="cnblogs",PassWord="987654",Age=33}            };            return list;        }        public UserModel GetUserFromID(string ID)        {            UserModel item = GetUserList().Where(a => a.ID == int.Parse(ID)).SingleOrDefault();            if (item != null)            {                return item;            }            else            {                return new UserModel();            }        }        public List<UserModel> GetAllUser()        {            return GetUserList();        }        public string UpdateUser(UserModel model)        {            return model.ToString();        }        public String GetUserName(string Name)        {            return "您好:" + Name;        }    }}

後面建立的用戶端傳參數要跟上面各個方法的參數相同,比如:Name,model等

4:Rest服務(RestService)

此處建立一個文字檔把它修改成.svc格式,在其裡面寫入:

<%@ ServiceHost Language="C#" Debug="true" Service="ServiceBll.UserBll" %>

web.config檔案內容:

<?xml version="1.0" encoding="utf-8"?><configuration>  <system.web>    <compilation debug="true" targetFramework="4.0" />  </system.web>  <system.serviceModel>    <behaviors>      <endpointBehaviors>        <behavior name="webHttp">          <webHttp helpEnabled="true"/>        </behavior>      </endpointBehaviors>      <serviceBehaviors>        <behavior name="MapConfigBehavior">          <!-- 為避免泄漏中繼資料資訊,請在部署前將以下值設定為 false 並刪除上面的中繼資料終結點 -->          <serviceMetadata httpGetEnabled="true"/>          <!-- 要接收故障異常詳細資料以進行調試,請將以下值設定為 true。在部署前設定為 false 以避免泄漏異常資訊 -->          <serviceDebug includeExceptionDetailInFaults="true"/>          <dataContractSerializer maxItemsInObjectGraph="2147483647"/>        </behavior>      </serviceBehaviors>    </behaviors>    <bindings>      <webHttpBinding>        <binding name="webHttpBindConfig" receiveTimeout="00:30:00" sendTimeout="00:30:00" maxReceivedMessageSize="104857600">          <readerQuotas maxStringContentLength="2147483647" maxArrayLength="2147483647"/>          <security mode="None"></security>        </binding>      </webHttpBinding>    </bindings>    <services>      <service name="ServiceBll.UserBll" behaviorConfiguration="MapConfigBehavior">        <endpoint binding="webHttpBinding" contract="IServiceInterface.IUser" bindingConfiguration="webHttpBindConfig" behaviorConfiguration="webHttp"/>      </service>    </services>  </system.serviceModel></configuration>



聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.