一个在vs2017中开发wcf的步骤

来源:互联网 发布:数组长度可以是变量吗 编辑:程序博客网 时间:2024/06/06 05:37

一、新建WCF服务应用程序

删除自动创建的WCF服务,然后添加新建WCF服务的接口和实现

接口如下:

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Channels;
using System.ServiceModel.Web;
using System.Text;


namespace WcfService1
{
    [ServiceContract]
    public interface ITaskInfo
    {
        [OperationContract]
        [WebGet(UriTemplate = "/DoWork?name={name}", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)]
        string DoWork(string name);
        [OperationContract]
        [WebGet(UriTemplate = "/Delete", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)]
        Stream Delete();
        [OperationContract]
        [WebGet(UriTemplate = "/Json")]
        string Json();
    }
}

实现如下

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Text;
using System.Web.Script.Serialization;
using System.Net.Http;
using System.ServiceModel.Channels;
using System.Runtime.Serialization.Json;


namespace WcfService1
{
    public class TaskInfo : ITaskInfo
    {
        public string DoWork(string name)
        {
            return "Hello World!:"+name;
        }


        public Stream Delete()
        {
            return GetStream(@"{""data"":""OK!!!!!!""}");
        }
        public string Json()
        {
            string res = null;
            Student stu = new Student
            {
                StuID = 3,
                StuName = "郭大侠"
            };
            Student stu1 = new Student
            {
                StuID = 31,
                StuName = "郭大侠1"
            };
            UserInfo u = new UserInfo("3", "郭大侠");
            UserInfo u1 = new UserInfo("31", "郭大侠1");
            List<Student> list = new List<Student>();
            List<UserInfo> list1 = new List<UserInfo>();
            list.Add(stu);
            list.Add(stu1);
            list1.Add(u);
            list1.Add(u1);
            using (MemoryStream ms = new MemoryStream())
            {
                XmlObjectSerializer sz = null;
                sz = new DataContractJsonSerializer(list.GetType());
                sz.WriteObject(ms, list);


                sz = new DataContractJsonSerializer(list1.GetType());
                sz.WriteObject(ms, list1);
                res = Encoding.UTF8.GetString(ms.ToArray());
            }
            return res;
        }
        private Stream GetStream(string str)
        {
            MemoryStream ms = new MemoryStream();
            StreamWriter sw = new StreamWriter(ms);
            sw.AutoFlush = true;
            sw.Write(str);
            ms.Position = 0;
            WebOperationContext.Current.OutgoingResponse.ContentType = "text/plain";
            return ms;
        }
        private Stream GetStreamJson(Object obj)
        {
            string str;
            if (obj is String || obj is Char)
            {
                str = obj.ToString();
            }
            else
            {
                JavaScriptSerializer serializer = new JavaScriptSerializer();
                str = serializer.Serialize(obj);
            }
            MemoryStream ms = new MemoryStream();
            StreamWriter sw = new StreamWriter(ms);
            sw.AutoFlush = true;
            sw.Write( new StringContent(str, Encoding.GetEncoding("UTF-8"), "application/json"));
            ms.Position = 0;
            WebOperationContext.Current.OutgoingResponse.ContentType = "application/json";
            return ms;
        }
    }
}

二、WCF配置

<?xml version="1.0" encoding="utf-8"?>
<configuration>
。。。。。。。。此处省略。。。。。。

  <system.serviceModel>
    <behaviors>
      <serviceBehaviors>
        <behavior>
          <!-- 浏览器可访问的设置项 -->
          <serviceMetadata httpGetEnabled="true" httpsGetEnabled="true"/>
          <serviceDebug includeExceptionDetailInFaults="false"/>
        </behavior>
      </serviceBehaviors>

      <endpointBehaviors>
        <behavior name="webBehavior">

<!-- 此处设为true,可以使得输出String时去掉json格式的外层引号-->
          <webHttp automaticFormatSelectionEnabled="true"/>
        </behavior>
      </endpointBehaviors>
    </behaviors>
    <protocolMapping>
        <add binding="basicHttpsBinding" scheme="https" />
    </protocolMapping>    
    <serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" />

    <services>
      <service name="WcfService1.TaskInfo">
        <endpoint behaviorConfiguration="webBehavior" binding="webHttpBinding"
          contract="WcfService1.ITaskInfo" />
      </service>
    </services>
  </system.serviceModel>
  <system.webServer>
    <modules runAllManagedModulesForAllRequests="true"/>
    <!--
        若要在调试过程中浏览 Web 应用程序根目录,请将下面的值设置为 True。
        在部署之前将该值设置为 False 可避免泄露 Web 应用程序文件夹信息。
      -->
    <directoryBrowse enabled="true"/>
  </system.webServer>

</configuration>

三、后台读取数据库架构

SqlHelper.cs,此处省略

UserInfo类程序如下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Web;


namespace WcfService1
{
    [DataContract]
    public class UserInfo
    {
        [DataMember]
        private string name;
        [DataMember]
        private string sex;
        public UserInfo(string name,string sex)
        {
            this.name = name;
            this.sex = sex;
        }
    }
}

四、发布设置

发布方法:web发布

服务器:localhost

站点名称:Default Web Site

目标URL:http://localhost

配置:release

五、结果:


原创粉丝点击