手记

WCF for ajaxToolkit

今天学习WCF,做了一个练习,最终的效果:

 

在数据库中创建表,插入数据,写好存储过程:

View Code

SET ANSI_NULLS ONGOSET QUOTED_IDENTIFIER ONGOCREATE TABLE [dbo].[Catalog](    [Catalog_nbr] [smallint] IDENTITY(1,1) NOT NULL,    [CatalogName] [nvarchar](100) NOT NULL, CONSTRAINT [PK_Catalog] PRIMARY KEY CLUSTERED (    [Catalog_nbr] ASC)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]) ON [PRIMARY]GOINSERT INTO [dbo].[Catalog] VALUES (N'1120934567'),(N'1034577856'),(N'1145324576'),(N'1034567889'),(N'Adfgjfghgg'),(N'ae45654657'),(N'1dhjyuryr5'),(N'brt4543w34'),(N'brsa2346gh'),(N'345gthu865'),(N'3uettr43f5'),(N'dgewqrytr4'),(N'dgh6876532')GOSET ANSI_NULLS ONGOSET QUOTED_IDENTIFIER ONGO-- =============================================-- Author:        Insus.NET-- Create date: 2013-01-18-- Description:    Get Catalog data for web services。-- =============================================CREATE PROCEDURE [dbo].[usp_Catalog_GetCatalogForWcfService](    @PrefixText NVARCHAR(MAX),    @Count INT)AS    DECLARE @W NVARCHAR(MAX) = @PrefixText + '%'EXECUTE('SELECT TOP (' + @Count + ') [CatalogName],[Catalog_nbr] FROM [dbo].[Catalog] WHERE [CatalogName] LIKE ''' + @w +'''')GO


在站点下,添加一个目录WCF,然后添加一个WCF Service,取名为Catalog.svc

<%@ ServiceHost Language="C#" Debug="true" Service="Insus.NET.Catalog" CodeBehind="~/App_Code/Catalog.cs" %>

上面的HTML注意一下Service属性,它应该包含命名空间与类别,更多参考:http://www.cnblogs.com/insus/archive/2013/01/19/2867629.html

接下来,我们应该看到App_Code目录有两个文件ICatalog接口与Catalog.cs类文件。

ICatalog

using System;using System.Collections.Generic;using System.Linq;using System.Runtime.Serialization;using System.ServiceModel;using System.ServiceModel.Web;using System.Text;// NOTE: You can use the "Rename" command on the "Refactor" menu to change the interface name "ICatalog" in both code and config file together.namespace Insus.NET{    [ServiceContract]    public interface ICatalog    {        [OperationContract]        [WebInvoke(Method = "POST", ResponseFormat = WebMessageFormat.Json)]        List<string> GetCatalog(string prefixText, int count);    }}

 

Catalog.cs

using System;using System.Collections.Generic;using System.Data;using System.Linq;using System.Runtime.Serialization;using System.ServiceModel;using System.ServiceModel.Activation;using System.Text;using System.Web;using System.Web.Script.Serialization;// NOTE: You can use the "Rename" command on the "Refactor" menu to change the class name "Catalog" in code, svc and config file together.namespace Insus.NET{    [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]    public class Catalog : ICatalog    {        BusinessBase objBusinessBase = new BusinessBase();        public List<string> GetCatalog(string prefixText, int count)        {            Parameter[] parameter = {                                     new Parameter ("@PrefixText",SqlDbType.NVarChar,-1,prefixText),                                    new Parameter ("@Count",SqlDbType.Int,4,count)                                };            DataTable objDatTable = objBusinessBase.GetDataToDataSet("usp_Catalog_GetCatalogForWcfService", parameter).Tables[0];            List<string> catalog = new List<string>();            foreach (DataRow dataRow in objDatTable.Rows)            {                string item = AjaxControlToolkit.AutoCompleteExtender.CreateAutoCompleteItem(dataRow["CatalogName"].ToString(),dataRow["Catalog_nbr"].ToString());                catalog.Add(item);            }            return catalog;        }    }}


写好接口与类别之后,在站点添加一个.aspx,如Default.aspx:

View Code

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %><!DOCTYPE html><html xmlns="http://www.w3.org/1999/xhtml"><head runat="server">    <title></title></head><body>    <form id="form1" runat="server">        <asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>        <asp:UpdatePanel ID="UpdatePanel1" runat="server">            <ContentTemplate>                Catalog:                <asp:TextBox ID="TextBoxCatalog" runat="server"></asp:TextBox>                <ajaxToolkit:AutoCompleteExtender ServiceMethod="GetCatalog"                    MinimumPrefixLength="1" ServicePath="~/WCF/Catalog.svc"                    TargetControlID="TextBoxCatalog"                    ID="AutoCompleteExtender1" runat="server" FirstRowSelected="false">                </ajaxToolkit:AutoCompleteExtender>            </ContentTemplate>        </asp:UpdatePanel>    </form></body></html>


ok,我们可以试运行一下看看。此时看到的,没有任何效果喔,为何,难道上面写的代码有错误?

哦,原来我们少了在Web.config配置<system.serviceModel>,Insus.NET已经配置好,参考就是了:

Web.config

<?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>  <connectionStrings>    <add name="InsusConnectionString" connectionString="Server=127.0.0.1\SQLSERVER2008R2;Initial Catalog=InsusSite;User ID=siteconnlogin;Password=aa43$98;Packet Size=8192;Max Pool Size=1000;" providerName="System.Data.SqlClient"/>  </connectionStrings>  <system.web>    <compilation debug="false" targetFramework="4.0" />    <pages>      <controls>        <add namespace="AjaxControlToolkit" assembly="AjaxControlToolkit" tagPrefix="ajaxToolkit"/>      </controls>    </pages>  </system.web>  <system.serviceModel>    <behaviors>      <endpointBehaviors>        <behavior name="CatalogAspNetAjaxBehavior">          <enableWebScript />        </behavior>            </endpointBehaviors>      <serviceBehaviors>        <behavior name="CatalogBehavior">          <serviceMetadata httpGetEnabled="true" />          <serviceDebug includeExceptionDetailInFaults="true" />        </behavior>                <behavior name="">          <serviceMetadata httpGetEnabled="true" />          <serviceDebug includeExceptionDetailInFaults="false" />        </behavior>      </serviceBehaviors>    </behaviors>    <serviceHostingEnvironment aspNetCompatibilityEnabled="true"      multipleSiteBindingsEnabled="true" />    <services>      <service behaviorConfiguration="CatalogBehavior" name="Insus.NET.Catalog">        <endpoint address="" binding="webHttpBinding" contract="Insus.NET.ICatalog" behaviorConfiguration="CatalogAspNetAjaxBehavior">          <identity>            <dns value="localhost"/>          </identity>        </endpoint>        <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/>      </service>        </services>  </system.serviceModel></configuration>

 

 

0人推荐
随时随地看视频
慕课网APP