您的位置:首页 > 运维架构

WCF-REST IEndpointBehavior 对Service 监控 用户访问验证

2013-05-24 21:27 501 查看
在Host_Opening 中添加 Endpoint

private void Host_Opening(object sender, EventArgs e)
{
ServiceHost host = sender as ServiceHost;

if (host == null)
{
return;
}

foreach (var endpoint in host.Description.Endpoints)
{
//添加用户访问Service 进行 监控,优先级高于 RestServiceBehavior
RestEndpointBehavior b1 = endpoint.Behaviors.Find<RestEndpointBehavior>();
if (b1 == null)
{
endpoint.Behaviors.Add(new RestEndpointBehavior());
}
}

}


RestEndpointBehavior.cs

namespace H.Utility.WCF
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel.Description;
using System.ServiceModel.Channels;
using System.ServiceModel.Dispatcher;
using System.ServiceModel.Configuration;

/// <summary>
/// 在服务端的Endpoint级别注入新的IDispatchOperationSelector,以便根据客户端发起的HTTP Request的Method来修改WCF消息的HttpRequestMessageProperty的Method
/// </summary>
public class RestEndpointBehavior : IEndpointBehavior
{
public void AddBindingParameters(ServiceEndpoint endpoint, BindingParameterCollection bindingParameters)
{

}

public void ApplyClientBehavior(ServiceEndpoint endpoint, ClientRuntime clientRuntime)
{

}

public void ApplyDispatchBehavior(ServiceEndpoint endpoint, EndpointDispatcher endpointDispatcher)
{
endpointDispatcher.DispatchRuntime.OperationSelector = new RestServiceOperationSelector(endpointDispatcher.DispatchRuntime.OperationSelector);
}

public void Validate(ServiceEndpoint endpoint)
{

}
}
}


RestServiceOperationSelector.cs

namespace H.Utility.WCF
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel.Dispatcher;
using System.ServiceModel.Channels;
using System.ServiceModel.Description;
using System.ServiceModel;
using System.Xml;
using H.BizEntity;

/// <summary>
/// 客户端调用Service 方法时会启动,优先级高于 IServiceBehavior
/// </summary>
public class RestServiceOperationSelector : IDispatchOperationSelector
{
private IDispatchOperationSelector m_Operation;

public RestServiceOperationSelector(IDispatchOperationSelector endpoint)
{
m_Operation = endpoint;
}

public string SelectOperation(ref Message message)
{
HttpRequestMessageProperty httpRequest = message.Properties[HttpRequestMessageProperty.Name] as HttpRequestMessageProperty;

//用户信息验证失败
//记录用户请求信息日志..
if (true)
{
throw new BizException("未经授权访问..");
}

return m_Operation.SelectOperation(ref message);
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐