【问题标题】:WCF: Why WebSecurity.CurrentUserId is -1?WCF:为什么 WebSecurity.CurrentUserId 是 -1?
【发布时间】:2018-06-20 08:41:11
【问题描述】:

我对使用 WCF 创建 Web 服务有点陌生。我只是有一个简单的问题。我正在使用 SimpleMembershipProvider 验证用户。在对我的 Web 服务的某些调用中,我需要检索当前的用户 ID。所以,我使用的是我在 MVC.NET 中使用的WebSecurity.CurrentUserId

为了更好地解释,这是我的 web.config,如您所见,我正在使用自定义验证器:

<system.serviceModel>
    ...
    ...
    ...
    <behaviors>
        <serviceBehaviors>
            <behavior name="behaviorCfg">
                ...
                ...
                ...
                <serviceCredentials>
                    <userNameAuthentication userNamePasswordValidationMode="Custom" customUserNamePasswordValidatorType="WarehouseWebService.WarehouseValidator, WarehouseWebService" />
                </serviceCredentials>
            </behavior>
        </serviceBehaviors>
    </behaviors>
    ...
    ...
    ...
    <serviceHostingEnvironment aspNetCompatibilityEnabled="true" minFreeMemoryPercentageToActivateService="0" multipleSiteBindingsEnabled="true" />
<system.serviceModel>

这是我的自定义验证器 (WarehouseValidator.cs):

public class WarehouseValidator : UserNamePasswordValidator
{
    public override void Validate(string userName, string password)
    {
        if (!WebSecurity.Initialized)
            WebSecurity.InitializeDatabaseConnection("warehouseConnStr", "UserProfile", "UserId", "UserName", false);

        if (!WebSecurity.Login(userName, password, true))
            throw new FaultException("Invalid username or password.");
    }
}

现在,在 web 服务上的一些调用(函数)中,我需要获取 CurrentUserId,我正在使用 WebSecurity.CurrentUserId,但它返回 -1。

所有其他属性似乎也没有被初始化。例如,WebSecurity.CurrentUserName 为空,WebSecurity.IsAuthenticated 为假。

这很奇怪,因为WebSecurity.Login(userName, password, true) 是成功的,我在我的网站 (MVC.NET) 中使用了相同的方法并且效果很好。

我知道这与 cookie 有关,我什至尝试过这样做:

FormsAuthentication.SetAuthCookie(userName, true);

但到目前为止没有任何效果!

知道为什么吗?

干杯

【问题讨论】:

    标签: c# asp.net asp.net-mvc wcf simplemembership


    【解决方案1】:

    如果您使用FormsAuthentication.SetAuthCookie(userName, true);,则需要在配置文件中将aspNetCompatibilityEnabled 设置为true,这表明您的服务将参与ASP.NET 管道;所以像 ASP.NET cookie 这样的项目是可用的。

    所以尝试添加

     <serviceHostingEnvironment aspNetCompatibilityEnabled="true" />
    

    【讨论】:

    • 我实际上在我的 web.config 中有它(我已经更新了我的问题)。放的地方合适吗?
    猜你喜欢
    • 1970-01-01
    • 2012-06-13
    • 2014-10-17
    • 1970-01-01
    • 1970-01-01
    • 2018-09-08
    • 1970-01-01
    • 1970-01-01
    • 2016-04-30
    相关资源
    最近更新 更多