技巧掌握之WCF獲取客戶端IP
作者:佚名
WCF獲取客戶端IP是一個比較基礎的知識點。對于一個剛剛學習WCF的朋友們來說,掌握之一基礎點是非常重要的,有助于我們將來的學習。
WCF在實際應用中,可以發現它能夠幫助我們實現許多功能需求。在這里我們就為大家詳細講解一下有關WCF獲取客戶端IP的實現方法。#t#
在公司的一個項目里面,使用WCF做通訊,里面需要取得使用WCF獲取客戶端IP,在服務器上做進一步的處理,但是讓人很失望的是WCF 3.0 里面并不能支持這個功能。還好,微軟在3.5的新版WCF中提供了這個方法。
不說廢話,直接看如何實現。
簡單定義一個WCF獲取客戶端IP的服務:
- 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);
- }
- }
在建立通道之后按照可以實現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>
以上就是有關WCF獲取客戶端IP的實現方法。
責任編輯:曹凱
來源:
博客園