WCF獲取客戶端IP應(yīng)用經(jīng)驗(yàn)分享
WCF開發(fā)工具的應(yīng)用范圍比較廣泛,可以幫助開發(fā)人員輕松的實(shí)現(xiàn)各種特定的功能需求。在這里我們可以了解到WCF獲取客戶端IP的相關(guān)操作方法,以此來進(jìn)一步對(duì)這一開發(fā)工具有一個(gè)深入的認(rèn)識(shí)。#t#
在公司的一個(gè)項(xiàng)目里面,使用WCF做通訊,里面需要取得使用WCF做客戶端的IP,在服務(wù)器上做進(jìn)一步的處理,但是讓人很失望的是WCF 3.0 里面并不能支持這個(gè)功能。
還好,微軟在3.5的新版WCF中提供了這個(gè)方法。
不說廢話,直接看如何實(shí)現(xiàn)WCF獲取客戶端IP。簡單定義一個(gè)服務(wù):
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Runtime.Serialization;
- using System.ServiceModel;
- using System.Text;
- namespace ClientInfoSample
- {
- [ServiceContract]
- public interface IService
- {
- [OperationContract]
- string GetData(string value);
- }
- }
在建立通道之后按照可以實(shí)現(xiàn)WCF獲取客戶端IP:
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Runtime.Serialization;
- using System.ServiceModel;
- using System.Text;
- using System.ServiceModel.Channels;
- namespace ClientInfoSample
- {
- public class MyService : IService
- {
- public string GetData(string value)
- {
- OperationContext context = OperationContext.Current;
- MessageProperties essageProperties =
context.IncomingMessageProperties;- RemoteEndpointMessageProperty endpointProperty =
- messageProperties [RemoteEndpointMessageProperty.Name]
- as RemoteEndpointMessageProperty;
- return string.Format("Hello {0}! Your IP address is {1}
and your port is {2}", value, endpointProperty.Address,
endpointProperty.Port);- }
- }
- }
- config:
- < ?xml version="1.0" encoding="utf-8" ?>
- < configuration>
- < system.web>
- < compilation debug="true" />
- < /system.web>
- < system.serviceModel>
- < services>
- < service name="ClientInfoSample.MyService"
behaviorConfiguration="ClientInfoSample.MyServiceBehavior">- < host>
- < baseAddresses>
- < add baseAddress = "http://localhost:8731/
Design_Time_Addresses/ClientInfoSample/MyService/" />- < /baseAddresses>
- < /host>
- < endpoint address ="" binding="wsHttpBinding"
contract="ClientInfoSample.IService">- < identity>
- < dns value="localhost"/>
- < /identity>
- < /endpoint>
- < endpoint address="mex" binding="mexHttpBinding"
contract="IMetadataExchange"/>- < /service>
- < /services>
- < behaviors>
- < serviceBehaviors>
- < behavior name="ClientInfoSample.MyServiceBehavior">
- < serviceMetadata httpGetEnabled="True"/>
- < serviceDebug includeExceptionDetailInFaults="False" />
- < /behavior>
- < /serviceBehaviors>
- < /behaviors>
- < /system.serviceModel>
- < /configuration>
以上就是對(duì)WCF獲取客戶端IP的相關(guān)介紹。