首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >为什么WebSecurity.CurrentUserId是-1?

为什么WebSecurity.CurrentUserId是-1?
EN

Stack Overflow用户
提问于 2018-01-11 12:48:07
回答 1查看 28关注 0票数 0

我是一个使用WCF创建web服务的新手。我只有一个简短的问题。我正在使用SimpleMembershipProvider验证用户。在对web服务的某些调用中,我需要检索当前的userid。所以,我使用的是我在MVC.NET中使用的WebSecurity.CurrentUserId

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

代码语言:javascript
复制
<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):

代码语言:javascript
复制
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.");
    }
}

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

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

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

我知道这和饼干有关,我甚至试过这样做:

代码语言:javascript
复制
FormsAuthentication.SetAuthCookie(userName, true);

但是到目前为止什么都没有起作用!

知道为什么吗?

干杯

EN

回答 1

Stack Overflow用户

发布于 2018-01-11 13:00:29

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

因此,尝试通过添加

代码语言:javascript
复制
 <serviceHostingEnvironment aspNetCompatibilityEnabled="true" />
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/48199934

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档