技巧掌握之WCF獲取客戶端IP
WCF在實(shí)際應(yīng)用中,可以發(fā)現(xiàn)它能夠幫助我們實(shí)現(xiàn)許多功能需求。在這里我們就為大家詳細(xì)講解一下有關(guān)WCF獲取客戶端IP的實(shí)現(xiàn)方法。#t#
在公司的一個(gè)項(xiàng)目里面,使用WCF做通訊,里面需要取得使用WCF獲取客戶端IP,在服務(wù)器上做進(jìn)一步的處理,但是讓人很失望的是WCF 3.0 里面并不能支持這個(gè)功能。還好,微軟在3.5的新版WCF中提供了這個(gè)方法。
不說廢話,直接看如何實(shí)現(xiàn)。
簡(jiǎn)單定義一個(gè)WCF獲取客戶端IP的服務(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 [RemoteEndpoint
MessageProperty.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 includeException
DetailInFaults="False" />- </behavior>
- </serviceBehaviors>
- </behaviors>
- </system.serviceModel>
- </configuration>
以上就是有關(guān)WCF獲取客戶端IP的實(shí)現(xiàn)方法。