我想通過使用web.config進行授權。 在我的用戶註冊中,它沒有使用ASP.NET配置。 我正在處理數據庫的登錄頁面。 我想保護管理頁面爲手動輸入其他人的地址。 我把這段代碼放在Web.config中。MVC 3位置允許web.config中的用戶
//Web.config
<location path="Product">
<system.web>
<authorization>
<allow users="*"/>
</authorization>
</system.web>
當管理員登錄網站由首頁其中有部分登錄頁面, 它會獲取用戶名和管理員是否通過數據庫或真或假。
[HttpPost]
public ActionResult Index(Customer model)
{
if (ModelState.IsValid)
{
//define user whether admin or customer
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["rentalDB"].ToString());
String find_admin_query = "SELECT admin FROM Customer WHERE userName = '" + model.userName + "' AND admin ='true'";
SqlCommand cmd = new SqlCommand(find_admin_query, conn);
conn.Open();
SqlDataReader sdr = cmd.ExecuteReader();
//it defines admin which is true or false
model.admin = sdr.HasRows;
conn.Close();
//if admin is logged in
if (model.admin == true) {
if (DAL.UserIsVaild(model.userName, model.password))
{
FormsAuthentication.SetAuthCookie(model.userName, true);
return RedirectToAction("Index", "Product");
}
}
//if customer is logged in
if (model.admin == false) {
if (DAL.UserIsVaild(model.userName, model.password))
{
FormsAuthentication.SetAuthCookie(model.userName, true);
return RedirectToAction("Index", "Home");
}
}
ModelState.AddModelError("", "The user name or password is incorrect.");
}
// If we got this far, something failed, redisplay form
return View(model);
}
然後我的問題是,我怎麼能由web.config中,而不是「*」定義用戶,喜歡用model.userName或model.admin?你能告訴我如何定義用戶嗎?謝謝。
謝謝你的回覆,當我把Roles.IsUserInRole(model.userName,「admin」),它不起作用[Authorize(Roles =「admin」)]。如果我需要創建AuthorizeAttribute來賦予特定角色,我該如何做到這一點?我是一名MVC初學者,那麼你能解釋一下如何實現它嗎?當我研究它時,我不知道該怎麼做。 – wholee1 2012-03-11 20:57:47