Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/275.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 在WCF请求中存储数据的位置_C#_Wcf_Web Services_Session - Fatal编程技术网

C# 在WCF请求中存储数据的位置

C# 在WCF请求中存储数据的位置,c#,wcf,web-services,session,C#,Wcf,Web Services,Session,我正在使用自定义用户名和密码验证我的WCF安全性。现在,我想在请求期间存储用户名,以便稍后在调用的方法中访问它。我该怎么做 描述我的问题的一些示例代码: public class CustomUserValidator : UserNamePasswordValidator { public override void Validate(string username, string password) { if (username == "aaa" &&

我正在使用自定义用户名和密码验证我的WCF安全性。现在,我想在请求期间存储用户名,以便稍后在调用的方法中访问它。我该怎么做

描述我的问题的一些示例代码:

public class CustomUserValidator : UserNamePasswordValidator
{
    public override void Validate(string username, string password)
    {
        if (username == "aaa" && password == "bbb")
        {
            // store username where i can get it in method called later.
            return;
        }
        throw new SecurityTokenException("Unknown Username or Password");
    }
}
现在调用的方法是:

public void WebServiceMethod()
{
    Database.User.Single(c => c.Username == /* username from above */);
}
BR

Andreas

您通常会通过发布自定义“主体”来完成此操作,这是通过
iaauthorizationpolicy
完成的;IIRC中,用户名通过评估上下文参数可用于身份验证策略。WCF中自定义主体的一般演练是,但是您可能需要在
Evaluate
中进行一些实验,以便在评估上下文中找到传入的用户名。特别是,如果其中任何一个键是“声明”字典,请查看它。并查看评估上下文中的
.Claims
——您应该在由
CustomUserValidator
发布的声明中找到一个“Claims”,其中包含用户名

然而,我已经做了你在以前的工作中描述的,IIRC使用上面的页面作为我的出发点,效果很好

一旦您发行了委托人,该委托人将正常通过以下方式提供:

string cn = Thread.CurrentPrincipal.Identity.Name;

要通过单个WCF请求存储任何类型的数据,Darin Dimitrov建议将一个简单的
IExtension
helper类连接到当前的
OperationContext
此处:

最简单的方法是将其存储在静态用户名属性中。更好的方法是编写一个自定义的WCF行为。@daryal,这在每个级别上都不好;a:WCF是多线程的,b:WCF可以在不同的点使用不同的线程(使线程静态不可靠)@MarcGravel您在每个级别上都是对的:),但是为了回答这个问题,应该提供实例模式和并发模式。这就是为什么我建议写一个行为。@daryal为什么写一个行为?identity在中有一个受良好支持的模型WCF@MarcGravell对于用户名,使用主体是可以的。但在一个复杂的场景中,如果您需要一些相关参数,我认为最好采用自定义行为。考虑一种情况,wcf调用头具有需要在数据库上持久化的标识符字段,并且相同的参数用于关联目的。