How do i get the invoked operation name within a WCF Message Inspector

筅森魡賤 提交于 2019-11-27 14:22:06
Kent Boogaart

It's not pretty, but this is what I did to get the operation name:

var action = OperationContext.Current.IncomingMessageHeaders.Action;
var operationName = action.Substring(action.LastIndexOf("/", StringComparison.OrdinalIgnoreCase) + 1);
Michael
var operationName = OperationContext.Current.IncomingMessageProperties["HttpOperationName"] as string;

This approach is similar to others presented here, but uses Path.GetFileName:

Path.GetFileName(OperationContext.Current.IncomingMessageHeaders.Action);

The return value of this method and the format of the path string work quite harmoniously in this scenario:

The characters after the last directory character in path. If the last character of path is a directory or volume separator character, this method returns String.Empty. If path is null, this method returns null.

OperationContext.Current.IncomingMessageHeaders.Action.Split('/').ToList().Last();

Little late to the party but I had to dig a little deeper than existing answers on this question because they seem to involve getting the action name and not the operation name. (Frequently they are the same so getting the action name does, in fact, get the operation name.)

Microsoft's Application Insights SDK Labs' WCF library makes this concerted effort:

private string DiscoverOperationName(OperationContext operationContext)
{
    var runtime = operationContext.EndpointDispatcher.DispatchRuntime;
    string action = operationContext.IncomingMessageHeaders.Action;
    if (!string.IsNullOrEmpty(action))
    {
        foreach (var op in runtime.Operations)
        {
            if (op.Action == action)
            {
                return op.Name;
            }
        }
    }
    else
    {
        // WebHttpDispatchOperationSelector will stick the
        // selected operation name into a message property
        return this.GetWebHttpOperationName(operationContext);
    }

    var catchAll = runtime.UnhandledDispatchOperation;
    if (catchAll != null)
    {
        return catchAll.Name;
    }

    return "*";
}

private string GetWebHttpOperationName(OperationContext operationContext)
{
    var name = WebHttpDispatchOperationSelector.HttpOperationNamePropertyName;
    if (this.HasIncomingMessageProperty(name))
    {
        return this.GetIncomingMessageProperty(name) as string;
    }

    return "<unknown>";
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!