代码改变世界

WCF寄宿在Windows Service (用post方式测试)

2017-11-06 16:52  多多多多多奈特  阅读(260)  评论(0)    收藏  举报

1.创建wcf项目

2.编写自己要用的接口并实现

[ServiceContract]
    public interface ITEService
    {
        [OperationContract]
        string GetStringData(string code);

        [OperationContract]
        JsonClass<LoginEmployeeOutput> Login(LoginEmployeeInput inputJson);

        [OperationContract]
        JsonClass<string> GetEmployeePhoto(EmployeePhoto inputJson);

        [OperationContract]
        JsonClass<Connections> GetConnection(ConnectionInput inputJson);

        [OperationContract]
        JsonClass<string> Enroll(EnrollInput inputJson);

        [OperationContract]
        JsonClass<EnrollOutput> GetEnrollResult(EnrollResult AutoGetEnrollRemark);

        [OperationContract]
        JsonClass<string> Authorization(EmployeeAuthorization inputJson);

        [OperationContract]
        JsonClass<List<Model.Employee>> SearchEmployee(SearchEmployeeInput inputJson);

        [OperationContract]
        JsonClass<string> NewEmployee(NewEmployee inputJson);

        [OperationContract]
        JsonClass<string> UploadPhoto(UploadEmployeePhoto inputJson);
    }
View Code
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
    public class TEService : ITEService
    {
        JavaScriptSerializer jsonSerialize = new JavaScriptSerializer();
        EmployeeBLL bll = new EmployeeBLL();
        ExceptionPolicy ep = new ExceptionPolicy();


        [WebInvoke(Method = "POST", BodyStyle = WebMessageBodyStyle.WrappedRequest, RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)]
        public string GetStringData(string code)
        {
            Employee emp = new Employee();
            emp.id = 1;
            emp.name = code;
            return jsonSerialize.Serialize(emp);
        }

        [WebInvoke(Method = "POST", BodyStyle = WebMessageBodyStyle.WrappedRequest, RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)]
        public JsonClass<LoginEmployeeOutput> Login(LoginEmployeeInput inputJson)
        {
            JsonClass<LoginEmployeeOutput> loginOutput = new JsonClass<LoginEmployeeOutput>();
            loginOutput.ResultCode = 0;
            loginOutput.Model = new LoginEmployeeOutput();
            try
            {
                
                loginOutput.ResultCode = bll.Login(inputJson);
                if (loginOutput.ResultCode == 1)
                {
                    loginOutput.Model = bll.GetEmployee(inputJson.LoginId);
                }
                return loginOutput;
            }
            catch (Exception ex)
            {
                ep.HandleException(DateTime.Now, "[TEService][Login]", ex.Message);
                return loginOutput;
            }
            
        }
...........................
View Code

3.编写配置文件

<system.serviceModel>
    <bindings>
      <webHttpBinding>
        <binding name="HttpJsonBinding" crossDomainScriptAccessEnabled="true"></binding>
      </webHttpBinding>
    </bindings>
    <services>
      <service name="WcfService.Service1" behaviorConfiguration="CaclulaterBehavior">
        <endpoint address="" 
                  binding="webHttpBinding" 
                  contract="WcfService.IService1"  
                  behaviorConfiguration="HttpBehavior"
                  bindingConfiguration="HttpJsonBinding"
                  >
          
        </endpoint>
      </service>
      <service name="WcfService.TEService" behaviorConfiguration="CaclulaterBehavior">
        <endpoint address=""
                  binding="webHttpBinding"
                  contract="WcfService.ITEService"
                  behaviorConfiguration="HttpBehavior"
                  bindingConfiguration="HttpJsonBinding"
                  >

        </endpoint>
      </service>
    </services>
    <behaviors>
      <serviceBehaviors>
        <behavior name="CaclulaterBehavior">
           
          <serviceMetadata httpGetEnabled="true"/>

          <serviceDebug includeExceptionDetailInFaults="false"/>
        </behavior>
      </serviceBehaviors>

      <endpointBehaviors>
        <behavior name="HttpBehavior">
          <webHttp/>
        </behavior>
      </endpointBehaviors>
    </behaviors>
  </system.serviceModel>

4.创建windows service

5.创建Service

public partial class Service : ServiceBase
    {
        ServiceHost host = new ServiceHost(typeof(TEService));
        public Service()
        {
            InitializeComponent();
        }

        protected override void OnStart(string[] args)
        {
            host.Open();
        }

        protected override void OnStop()
        {
            host.Close();
        }
    }
View Code

6.添加安装程序

  在service设计界面右键添加即可

7.添加服务的配置文件  

  将wcf中的配置文件内容拷贝过来即可

8.安装windows服务

  我用的批处理

  安装命令 

  %SystemRoot%\Microsoft.NET\Framework\v4.0.30319\installutil.exe WindowsService.exe
  pause

  卸载命令

    %SystemRoot%\Microsoft.NET\Framework\v4.0.30319\installutil.exe /u WindowsService.exe

9. 调用测试

  

JavaScriptSerializer jsonSerialize = new JavaScriptSerializer();

            string url = "http://localhost:3060/NewEmployee";
            //定义request并设置request的路径
            WebRequest request = WebRequest.Create(url);

            //定义请求的方式
            request.Method = "POST";

            Model.NewEmployee ne = new Model.NewEmployee();
            ne.EnglishName = "Test t";
            ne.ChineseName = "测试测";
            ne.CWRNo = "cwr00000001";
            ne.CWRExpiryDate = DateTime.Now.ToShortDateString();
            ne.PIN = "456978";
            ne.EmployeeCode = "SE456978";

            string inputJson = "{\"inputJson\":" + jsonSerialize.Serialize(ne) + "}";


            //设置参数的编码格式,解决中文乱码
            byte[] byteArray = Encoding.UTF8.GetBytes(inputJson);

            //设置request的MIME类型及内容长度
            request.ContentType = "application/json;";
            request.ContentLength = byteArray.Length;

            //打开request字符流
            Stream dataStream = request.GetRequestStream();
            dataStream.Write(byteArray, 0, byteArray.Length);
            dataStream.Close();

            //定义response为前面的request响应
            WebResponse response = request.GetResponse();

            //获取相应的状态代码
            Console.WriteLine(((HttpWebResponse)response).StatusDescription);

            //定义response字符流
            dataStream = response.GetResponseStream();
            StreamReader reader = new StreamReader(dataStream);
            string responseFromServer = reader.ReadToEnd();//读取所有

           // RespClass<LoginEmployeeOutput> jsonModel = jsonSerialize.Deserialize<RespClass<LoginEmployeeOutput>>(responseFromServer);
            Console.WriteLine(responseFromServer);

            //关闭资源
            reader.Close();
            dataStream.Close();
            response.Close();
View Code