【问题标题】:Sending userID to WCF service without sending as method parameter [duplicate]将用户 ID 发送到 WCF 服务而不作为方法参数发送 [重复]
【发布时间】:2012-09-03 19:17:47
【问题描述】:

可能重复:
How to add custom soap headers in wcf?

场景如下:

我有一个 WCF 服务,我们称之为“BusinessService”。

我还有一个网络应用程序,它有这个服务的客户端来发送请求。

我希望能够记录谁正在向我的服务发送更新;因此,我的 BusinessService 有一个名为 _userID 的私有字符串成员以及设置此 _userID 的方法,该类如下所示:

public class BusinessService : IBusinessService
{
    private string _userID;

    public void SetUserID(string userID)
    {
        _userID = userID;
    }

    public void UpdateCustomer(Customer customer)
    {
        // update customer here.
    }
}

由于上述类的编写方式(因为为 WCF 服务创建自定义 custructor 并不容易,我可以在其中传递用户 ID),所以我的 Web 应用程序是这样编写的:

public class WebApp
{
    private string _userID; // on page load this gets populated with user's id

    // other methods and properties

    public void btnUpdateCustomer_Click(object sender, EventArgs e)
    {
        Customer cust = new Customer();

        // fill cust with all the data.

        BusinessServiceClient svc = InstantiateWCFService();
        svc.UpdateCustomer(cust);
        svc.Close();
    }

    private BusinessServiceClient InstantiateWCFService()
    {
        BusinessServiceClient client = new BusinessServiceClient("EndPointName");
        client.SetUserID(_userID);
        return client;
    }
}

查看存储的数据时,没有为用户 ID 保存任何内容。

是否有某种形式的设计模式或功能允许我记录谁在进行某些更改,而我的服务在每个方法调用中都需要用户 ID?

【问题讨论】:

    标签: c# .net wcf


    【解决方案1】:

    您也可以在消息头中添加用户ID。请参阅此link。此方法在 WCF 之前的 Web 服务中使用。

    【讨论】:

      【解决方案2】:

      我知道你会认为这很极端,但有优势

      使用用户名进行身份验证并接受任何密码。并使用会话。这要求用户在执行任何操作之前传递用户 ID。而且他们不需要在每个方法调用中都发送用户 ID。

      http://msdn.microsoft.com/en-us/library/ff648840.aspx

      【讨论】:

        【解决方案3】:

        您可以使用InstanceContextMode property of the ServiceBehavior attribute 为每个会话创建 WCF 服务类。 (注意这需要 wsHttpBinding 或其他会话感知绑定。)

        [ServiceBehavior(InstanceContextMode=InstanceContextMode.PerSession)]
        public class BusinessService : IBusinessService
        

        那么您需要做的就是更新您的客户端代码以在每个会话中使用代理类的单个实例。一种简单的方法是将代理类隐藏在 Session 对象中:

        private BusinessServiceClient _client;
        
        void Page_Init()
        {
            if (Session["client"] == null) 
            {
                _client = InstantiateWCFService();
                Session["client"] = _client;
            }
            else
            {
                _client = (BusinessServiceClient) Session["client"];
            }
        }
        

        现在使用共享对象_client 而不是每次都实例化它。这样,会话和_uid 将在服务端按会话保留。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2013-06-26
          • 2014-11-30
          • 1970-01-01
          • 2014-05-31
          • 2015-01-06
          • 2011-07-15
          • 1970-01-01
          相关资源
          最近更新 更多