ASP.NET 身份 - 匿名配置文件

ASP.NET Identity - Anonymous profiles

我想使用匿名配置文件来存储和使用配置文件数据而无需经过身份验证。页面上描述了如何启用匿名配置文件 https://msdn.microsoft.com/en-us/library/ewfkf772(v=vs.100).aspx

Profiles can also work with anonymous users. Support for anonymous profiles is not enabled by default, so you must explicitly enable it. In addition, when you define profile properties in the Web.config file, you must explicitly make them available individually for anonymous users. Profile properties do not support anonymous access by default because profiles may be designed to work with authenticated users, and many properties are likely to pertain to personal information that is not available for anonymous users.

但我不确定我是否可以使用匿名用户的配置文件数据。它说,默认情况下我不能使用配置文件数据。但不是默认情况下,我可以使用匿名用户的配置文件数据吗?如果 "yes" 那么我应该怎么做? 我糊涂了...

回答

可以使用匿名配置文件。它们让我们可以将配置文件数据(例如邮政编码)与匿名用户相关联。当然,配置文件数据仅在 ASP.NET 可以通过 cookie(或查询字符串参数)识别匿名用户时才相关:

But I'm not sure, that I can use profile data for anonymous users.

我们可以。 我刚刚在我的本地机器上用 ASP.NET MVC 测试了这个。

...and if "yes" then what should I do?

首先,将以下内容添加到 web.config 文件的 system.web 部分。它告诉 ASP.NET 跟踪匿名用户,添加单个配置文件 属性,并使用我们的默认数据库连接配置提供程序(假设我们有一个名为 DefaultConnection 的连接字符串)

<anonymousIdentification enabled="true" />   
<profile defaultProvider="SqlProvider" >
  <properties>
    <add name="PostalCode"
      type="System.String"
      allowAnonymous="true" />               
  </properties>
  <providers>
    <clear />
    <add name="SqlProvider"
         type="System.Web.Profile.SqlProfileProvider"
         connectionStringName="DefaultConnection" />
  </providers>      
</profile>  

完成后,ASP.NET 将允许我们get/set 配置文件属性如下:

// get
var postalCode = Profile.GetPropertyValue("PostalCode") as string;

// set
Profile.SetPropertyValue("PostalCode", "V8K 1B1");
Profile.Save();

注意:您必须在您的数据库上设置 Profiles 才能工作(否则 ASP.NET 会抱怨找不到存储过程。)设置 Profiles 的一种方法是 运行 aspnet_regsql 像这样在你的数据库上。

aspnet_regsql -S "myDbServer" -A p -d "myDbName" -E

有关 aspnet_regsql 标志的更多信息,运行 aspnet_regsql -? 文档。 -A p 设置配置文件,-E 使用集成安全性。

另请参阅:

对于其他方法和更多细节,这里有一些其他链接: