开发平台:
VS2008 RTM
SQL SERVER 2005 企业版
ASP.NET 3.5 Extensions CTP
MVCToolkit
1.新建一个MVC的工程,随便取个名字吧
2.建立SQL数据库,命名为mvc_test
3.运行C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\aspnet_regSQL.exe来生成该数据库的Membership结构
下一步后点击完成.
4.到这里Membership的结构已经生成好了
5.下面在Web.Config中加入SQL连接字符串
<connectionStrings>
<remove name="LocalSQLServer" />
<add name="LocalSQLServer" connectionString="Data Source=.;Initial Catalog=mvc_test;Persist Security Info=True;User ID=sa;Password=" providerName="System.Data.SqlClient" />
</connectionStrings>
这里注意不要修改配置的name="LocalSqlServer"
6.继续在Web.Config中加入membership的配置节点(system.web节点下添加)
<membership defaultProvider="SQLMembershipProvider">
<providers>
<add name="SQLMembershipProvider" passwordFormat="Clear" type="System.Web.Security.SqlMembershipProvider" connectionStringName=" LocalSQLServer " applicationName="mvc_test" enablePasswordRetrieval="true" enablePasswordReset="true" requiresQuestionAndAnswer="false" requiresUniqueEmail="false" minRequiredPasswordLength="4" minRequiredNonalphanumericCharacters="0"/>
</providers>
</membership>
7. 将<authentication mode="Windows"/>改为<authentication mode="Forms"/>
8.在Views/Home目录下建立一个MVC View Content Page,命名为Login.aspx
接着选取Views/Shared/Site.Master母版页
8.Login.aspx这个页面放入一个User Control就行了.所以还要建一个MVC View User Control
命名为Login.ascx,建立在Views/Shared目录下面
9.将以下代码替换自动生成的:
<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl" %>
<%if (!Page.User.Identity.IsAuthenticated)
{%>
<form action='<%= Url.Action( new { Action="Login",Controller="Home"}) %>' method="post">
用户名:<%=Html.TextBox("Username")%>
密码:<%=Html.Password("Password")%><%= ViewData.ContainsDataItem("Message")? ViewData["Message"]:""%><%=Html.SubmitButton("Submit", "确定")%>
</form>
<%}
else
{%>
<span>您好!
<%=Page.User.Identity.Name %> <%=Html.ActionLink<MVC_Login.Controllers.HomeController>(c => c.Logout()
, "退出登陆", new { id = "LogoutLink" })%></span>
<%} %>
10.引用User Control 的方法是
<%= Html.RenderUserControl("~/Views/Shared/Login.ascx") %>
将这条代码加到Login.aspx和母版页合适位置.
11.打开Controllers/HomeController.cs文件
加入以下2个 controller action
[ControllerAction]
public void Login()
{
if (!ControllerContext.HttpContext.User.Identity.IsAuthenticated)
{
if (Request.RequestType == "POST")
{
string userName = Request.Form["Username"];
string password = Request.Form["Password"];
if (Membership.ValidateUser(userName, password))
{
FormsAuthentication.SetAuthCookie(userName, true);
//Set cookie and redirect
RedirectToAction("Index");
}
else
{
ViewData.Add("Message", "用户名或密码错误");
}
}
}
RenderView("Login");
}
[ControllerAction]
public void Logout()
{
FormsAuthentication.SignOut();
RedirectToAction("Index");
}
12.接下来从网上下载MVCToolkit.dll,没有这个是绝对不行滴~
下载地址: http://asp.net/downloads/3.5-extensions/MVCToolkit.zip
将里面的MVCToolkit.dll引用一下.现在可以运行了.
对了.自己先建一个Membership用户进行测试,MVC的注册还没有做