开发者

How to get OperationDescription from OperationContext on AfterReceiveRequest in WCF?

In my implementation of IDispatchMessageInspector on the AfterReceiveRequest I want to check if an OperationBehavior is applied on the current operation being called. So I need to access OperationDescription of the operation that's about to get invoked?? Any direct way instead of having to compare the Action of the current operation with all the i开发者_StackOverflown the DispatchRuntime?

Thanks..


I had the same issue and solved through below way.

OperationContext ctx = OperationContext.Current;
ServiceDescription hostDesc = ctx.Host.Description;
ServiceEndpoint endpoint = hostDesc.Endpoints.Find(ctx.IncomingMessageHeaders.To);
string operationName = ctx.IncomingMessageHeaders.Action.Replace(
  endpoint.Contract.Namespace + endpoint.Contract.Name + "/", "");
OperationDescription operation =
endpoint.Contract.Operations.Find(operationName);

This is suggested solution at msdn forum


The suggested answer by Noel Bj Kim works, except this line is problematic:

ServiceEndpoint endpoint = hostDesc.Endpoints.Find(ctx.IncomingMessageHeaders.To);

I've found that when hosting a WCF service in IIS, the Uri used in the service may not exactly match the one being requested - in my case "localhost" was requested but the service was actually using the machine name (e.g. "pc1.domain1.net"), not "localhost".

My solution, which may not work for everyone's circumstances, is to just do a partial match based on the scheme and the path. This effectively allows a match of http://localhost/Service1 to http://pc1.domain.net/Service1.

/// <summary>
/// Find a service endpoint by partially matching the uri, but only against the Scheme and PathAndQuery elements.
/// This avoids issues with IIS hosting, where the actual Uri stored in the ServiceEndpoint may not exactly
/// match the one used in configuration.
/// </summary>
/// <param name="uri">Uri to match against</param>
/// <returns>A matching ServiceEndpoint, or null if no match was found.</returns>
private ServiceEndpoint FindServiceEndpointBySchemeAndQuery(Uri uri)
{
    foreach (var endpoint in OperationContext.Current.Host.Description.Endpoints)
    {
        if (endpoint.Address.Uri.Scheme == uri.Scheme
            && endpoint.Address.Uri.PathAndQuery == uri.PathAndQuery)
        {
            return endpoint;
        }
    }
    return null;
}

Called like this:

ServiceEndpoint endpoint = FindServiceEndpointBySchemeAndQuery(ctx.IncomingMessageHeaders.To);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜