无法将“System.Web.Profile.DefaultProfile”类型的对象强制转换为“ProfileCommon”类型

时间:2011-04-21 19:01:36

标签: asp.net

我看到了这个错误:

无法将“System.Web.Profile.DefaultProfile”类型的对象转换为“ProfileCommon”类型。

关于以下代码:

ProfileCommon p =(ProfileCommon)ProfileCommon.Create(TextUsername.Text,true);

我不确定为什么......

2 个答案:

答案 0 :(得分:3)

同意 theChrisKent 。在web.config中看起来像问题

查看以下示例:如何在asp.net中获取ProfileCommon对象

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="GetProfile" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>Untitled Page</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        User Name:<asp:TextBox ID="txtUserName" runat="server"/>
        <asp:Button ID="cmdGet" runat="server" OnClick="cmdGet_Click" Text="Get Profile" /><br />
        <asp:Label ID="lbl" runat="server" Text=""/>
    </div>
    </form>
</body>
</html>

文件:Default.aspx.cs

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

public partial class GetProfile : System.Web.UI.Page
{
  protected void cmdGet_Click(object sender, EventArgs e)
  {
    ProfileCommon profile = Profile.GetProfile(txtUserName.Text);
        if (profile.LastUpdatedDate == DateTime.MinValue)
        {
            lbl.Text = "No user match found.";
        }
        else
        {
            lbl.Text = "This user lives in " + profile.FirstName;
        }
  }
}

文件:Web.config

<?xml version="1.0"?>
<configuration>
  <system.web>
    <profile>
      <properties>
        <add name="FirstName" type="String" serializeAs="Binary"/>
        <add name="LastName" type="String" serializeAs="Xml"/>
        <add name="DateOfBirth" type="DateTime" serializeAs="String"/>
      </properties>
    </profile>
  </system.web>
</configuration>

修改

此示例仅在项目类型为website时才有效。如果要在Web Application中使用ProfileCommon对象,请执行以下链接

Converting Profile Object Code

EDIT -II

根据您的评论,以下链接可能会对您有所帮助

ASP.NET Profiles in Web Application Projects

答案 1 :(得分:1)

如果未定义<profile />部分,请检查您的web.config,ASP.NET会创建一个类型为DefaultProfile的配置文件对象,这可能会导致您的错误。

以上内容仅适用于网站而非Web应用程序。由于您已表明您正在使用Web应用程序,因此您应该知道:

  • Visual Studio不会为Web应用程序生成ProfileCommon对象
  • 您必须使用ProfileBase.GetPropertyValue(PropertyName)
  • 访问您的个人资料属性

所以你可以得到这样的房产(例如下面的文章):

DateTime DOB = Convert.ToDateTime(HttpContext.Current.Profile.GetPropertyValue("DateOfBirth"));

有关更多信息/示例,请参阅此文章:http://weblogs.asp.net/anasghanem/archive/2008/04/12/the-differences-in-profile-between-web-application-projects-wap-and-website.aspx