在 WCF 中使用属性

本文关键字:属性 WCF | 更新日期: 2023-09-27 18:31:43

我有一个服务,我想使用来自客户端的属性:

[ServiceContract]
public interface IMyAPI
{
    string UserName { [OperationContract] get; [OperationContract] set; }
    string Password { [OperationContract] get; [OperationContract] set; }
    [OperationContract]
    bool StockQuery(string partNo);
}
public class MyAPI : IMyAPI
{
    public string UserName { get; set; }
    public string Password { get; set; }
    private void CheckSecurity()
    {
        if(this.UserName != "test" && this.Password != "123")
        {
            throw new UnauthorizedAccessException("Unauthorised");
        }
    }
    public bool StockQuery(string partNo)
    {
        this.CheckSecurity();
        if(partNo == "123456")
        {
            return true;
        }
        return false;
    }
}

然后在我的客户上,我做:

Testing.MyAPIClient client = new Testing.MyAPIClient();
client.set_UserName("test");
client.set_Password("123");
Console.WriteLine(client.StockQuery("123456"));
Console.ReadLine();

问题是,当我调试时,没有设置UserNamePassword,它们都是空的

在 WCF 中使用属性

默认情况下,

WCF 将创建服务的新实例来为每个调用提供服务(PerCall 实例化),因此不会记住属性集。

您需要在StockQuery服务呼叫中传递安全详细信息。

[OperationContract]
bool StockQuery(string partNo,String userName,String password);
public bool StockQuery(string partNo,String userName,String password)
{
    this.CheckSecurity(userName,password);
    if(partNo == "123456")
    {
        return true;
    }
    return false;
}

您可以使用 PerSession 实例化来摆脱此方法,其中相同的实例将用于为每个客户端提供服务。

[ServiceContract(SessionMode = SessionMode.Required)]
public interface IMyAPI
{
...
}
[ServiceBehavior(InstanceContextMode = InstanceContextMode.PerSession)] 
public class MyAPI : IMyAPI
{
...
}

但是,与其重新发明轮子,我会考虑使用一些内置的 WCF 安全性。