Задача:
Вывести данные, к примеру, список пользователей, в Grid, используя связку ExtJS (клиент) и службы WCF, размещенной в IIS на локальной машине (сервер)
1. Серверная часть реализована на платформе .NET Framework 4.7.2, состоит из двух файлов cs:
using System.Collections.Generic; namespace WcfService1 { public class Service1 : IService1 { public UserList GetListUsers(int value) { var response = new UserList(); var listUser = new List<User>(); var user1 = new User { UserId = 1, UserName = "User 1" }; var user2 = new User { UserId = 2, UserName = "User 2" }; var user3 = new User { UserId = 3, UserName = "User 3" }; var user4 = new User { UserId = 4, UserName = "User 4" }; var user5 = new User { UserId = 5, UserName = "User 5" }; listUser.Add(user1); listUser.Add(user2); listUser.Add(user3); listUser.Add(user4); listUser.Add(user5); response.ListUser = listUser; return response; } } }
и второй файл:
using System.Collections.Generic; using System.ComponentModel; using System.Runtime.Serialization; using System.ServiceModel; using System.ServiceModel.Web; namespace WcfService1 { [ServiceContract] public interface IService1 { [Description("Список пользователей")] [OperationContract] [WebInvoke(Method = "*", BodyStyle = WebMessageBodyStyle.Bare, RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)] UserList GetListUsers(int value); } [DataContract] public class UserList { [DataMember] public List<User> ListUser{ get; set; } } [DataContract] public class User { [DataMember] public int? UserId { get; set; } [DataMember] public string UserName { get; set; } } }
файл конфигурации службы (Web.config):
<?xml version="1.0"?> <configuration> <appSettings> <add key="aspnet:UseTaskFriendlySynchronizationContext" value="true" /> </appSettings> <system.web> <compilation debug="true" targetFramework="4.7.2" /> <httpRuntime targetFramework="4.7.2"/> </system.web> <system.serviceModel> <bindings> <basicHttpBinding> <binding closeTimeout="02:30:00" openTimeout="02:30:00" receiveTimeout="02:30:00" sendTimeout="02:30:00" maxBufferPoolSize="2147483647" maxBufferSize="2147483647" maxReceivedMessageSize="2147483647" transferMode="Streamed"> <readerQuotas maxDepth="2000000" maxStringContentLength="2147483647" maxArrayLength="2147483647" maxBytesPerRead="2147483647" maxNameTableCharCount="2147483647"/> </binding> </basicHttpBinding> <webHttpBinding> <!--allow big messages: 10mb = 10 * 1048576 = 10485760--> <binding maxBufferPoolSize="2147483647" maxBufferSize="2147483647" maxReceivedMessageSize="2147483647" sendTimeout="00:10:00" receiveTimeout="00:10:00"> <readerQuotas maxDepth="2000000" maxStringContentLength="2147483647" maxArrayLength="2147483647" maxBytesPerRead="2147483647" maxNameTableCharCount="2147483647"/> </binding> </webHttpBinding> </bindings> <services> <service name="WcfService1.Service1"> <endpoint address="rest" contract="WcfService1.IService1" binding="webHttpBinding" behaviorConfiguration="webHttp"/> <endpoint address="" contract="WcfService1.IService1" binding="basicHttpBinding"/> </service> </services> <behaviors> <serviceBehaviors> <behavior> <!-- To avoid disclosing metadata information, set the values below to false before deployment --> <serviceMetadata httpGetEnabled="true" httpsGetEnabled="true"/> <!-- To receive exception details in faults for debugging purposes, set the value below to true. Set to false before deployment to avoid disclosing exception information --> <serviceDebug includeExceptionDetailInFaults="false"/> </behavior> </serviceBehaviors> <endpointBehaviors> <behavior name="webHttp"> <webHttp helpEnabled="true" /> </behavior> </endpointBehaviors> </behaviors> <protocolMapping> <add binding="basicHttpsBinding" scheme="https" /> </protocolMapping> <serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" /> </system.serviceModel> <system.webServer> <modules runAllManagedModulesForAllRequests="true"/> <!-- To browse web app root directory during debugging, set the value below to true. Set to false before deployment to avoid disclosing web app folder information. --> <directoryBrowse enabled="true"/> <httpProtocol> <customHeaders> <add name="Access-Control-Allow-Origin" value="*" /> <add name="Access-Control-Allow-Headers" value="Content-Type" /> <add name="Access-Control-Allow-Methods" value="POST, GET, OPTIONS" /> </customHeaders> </httpProtocol> </system.webServer> </configuration>
Публикуем службу (http://localhost:8080/Test1/Service1.svc)
2. Клиентская часть реализована на ExtJS 4.2.1 и состоит из двух файлов.
GridAjax.html
<html> <head> <title>Sencha Grid Ajax</title> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <link rel="stylesheet" type="text/css" href="/ext-4.2.1/examples/shared/example.css" /> <script type="text/javascript" src="/ext-4.2.1/examples/shared/include-ext.js"></script> <script type="text/javascript" src="/ext-4.2.1/examples/shared/options-toolbar.js"></script> <script type="text/javascript" src="GridAjax.js"></script> <body> <p>Простая таблица grid и хранилище Ext.data.Store</p> <div id="example-grid"></div> </body> </html>
GridAjax.js
Ext.require([ 'Ext.data.*', 'Ext.grid.*' ]); Ext.Ajax.cors = true; Ext.Ajax.useDefaultXhrHeader = false; Ext.onReady(function(){ Ext.define('User',{ extend: 'Ext.data.Model', fields: [ { name: 'UserId', type: 'int' }, { name: 'UserName', type: 'string' } ] }); var store = Ext.create('Ext.data.Store', { model: 'User', autoLoad: true, proxy: { type: 'ajax', url: 'http://localhost:8080/Test1/Service1.svc/rest/GetListUsers', reader: { idProperty: 'UserId', root: 'ListUser' }, writer: { type: 'json', root: 'User', allowSingle: true, writeAllFields: false } } }); var grid = Ext.create('Ext.grid.Panel', { frame: true, title: 'Grid AJAX', store: store, columns: [ {text: "UserId", flex: 1, dataIndex: 'UserId'}, {text: "UserName", width: 180, dataIndex: 'UserName'} ], renderTo:'example-grid', width: 540, height: 200 }); });
Результат: