【问题标题】:Pass User info to WCF Web service with WCF method vs with Soap header使用 WCF 方法与使用 Soap 标头将用户信息传递给 WCF Web 服务
【发布时间】:2014-11-18 07:51:43
【问题描述】:

我的 WCF Web 服务提供所有数据操作操作,我的 ASP .Net Web 应用程序提供用户界面。

我需要使用许多 wcf 方法将用户信息从 ASP .Net 应用程序传递到 WCF 应用程序。

在将用户信息从 Web 应用程序传递到 Web 服务方面,哪一种方法更好?

1) 使用 SOAP 标头传递用户信息?

ASP .Net 应用程序必须将 WCF Webservice 客户端的实例数保持为使用 Web 应用程序登录的用户数。假设 4000 个用户同时处于活动状态,Web 应用程序必须维护 4000 个 WCF webserice 客户端实例。 它有任何性能问题吗?

2) 将每个方法调用作为附加参数传递用户信息?

每个方法都必须添加这个附加参数来传递用户信息,这似乎不是一个优雅的解决方案。

请提出建议。

问候, 佛法

【问题讨论】:

    标签: asp.net wcf wcf-security


    【解决方案1】:

    我认为最好在您发送到 WCF 服务的每条消息的标头中传递某种用户 ID。这很容易做到,如果需要,这是获取用户信息+在服务端授权用户的好方法。并且您不需要 4000 个 Web 服务客户端实例。

    您只需要在客户端使用客户端消息检查器创建行为(并将其注册到您的配置中)。例如:

    public class AuthClientMessageInspector: IClientMessageInspector
    {
    
        public void AfterReceiveReply(ref Message reply, object correlationState)
        {            
        }
    
        public object BeforeSendRequest(ref Message request, IClientChannel channel)
        {            
            request.Headers.Add(MessageHeader.CreateHeader("User", "app", "John"));
            return null;
        }
    }
    
    public class ClientBehavior : IEndpointBehavior
    {
    
        public void AddBindingParameters(ServiceEndpoint endpoint, BindingParameterCollection bindingParameters)
        {            
        }
    
        public void ApplyClientBehavior(ServiceEndpoint endpoint, ClientRuntime clientRuntime)
        {
            foreach (var operation in endpoint.Contract.Operations)
            {
                operation.Behaviors.Find<DataContractSerializerOperationBehavior>().MaxItemsInObjectGraph = Int32.MaxValue;
            } 
    
            var inspector = new AuthClientMessageInspector();
            clientRuntime.MessageInspectors.Add(inspector);
        }
    
        public void ApplyDispatchBehavior(ServiceEndpoint endpoint, EndpointDispatcher endpointDispatcher)
        {            
        }
    
        public void Validate(ServiceEndpoint endpoint)
        {            
        }
    }
    

    并从您的服务端提取它:

    var headers = OperationContext.Current.IncomingMessageHeaders;
    var identity = headers.GetHeader<string>("User", "app");
    

    【讨论】:

    • 那个检查员使用固定的用户名。如何更改它以使用当前用户?
    • 我使用“固定”用户只是为了不让示例过于复杂。取而代之的是,您应该使用您在项目中拥有的任何用户身份信息。例如,它可以是从数据库中提取的当前用户 ID。不幸的是,不知道您项目的内部细节,很难给您提供可以按原样工作的示例。
    • 是一个 ASP.NET MVC 5 门户,我想使用当前登录用户的身份,该用户正在调用控制器上的操作并且该操作正在调用 WCF 服务。信息是否清晰且足够?谢谢
    • 尝试在您的客户端消息检查器中使用 HttpContext.Current.User.Identity.GetUserId()
    • 请添加如何在MVC应用程序中注册wcf行为和Inspector?
    猜你喜欢
    • 1970-01-01
    • 2013-04-08
    • 2011-04-19
    • 1970-01-01
    • 2012-07-03
    • 2015-12-20
    • 1970-01-01
    • 1970-01-01
    • 2014-01-01
    相关资源
    最近更新 更多