談談在體驗ASP.NET MVC 4 的過程中遇到的那些令人蛋疼的事(1)

來源:互聯網
上載者:User

如果您已經試用過ASP.NET MVC 4,在AccountController裡你肯定會注意到這樣的變化:

[Authorize]
public class AccountController : Controller
{

//
// GET: /Account/LogOn

[AllowAnonymous]
public ActionResult LogOn()
{
return ContextDependentView();
}
}

在這段代碼中與MVC 3中的區別就是這裡把AccountController裡所有的Action都加上了Authorize過濾器,在其中允許直接存取的Action則加上了AllowAnonymous。這且不說,接下來兔紙就遇到了個讓人蛋疼的問題,

我們都之都在ASP.NET MVC 3.0中有一個很強大的功能,那就是Remote。可以遠程和資料庫互動驗證Model,比如在註冊的時候可以驗證使用者名稱是否重複。具體的我也就不口水了,在網上都可以查到。在這簡單地貼一下代碼吧:

[Remote("CheckUserNameExists", "Account", ErrorMessage = "Sorry! In the registered members the name already exists. Please enter a different name.")]
[Display(Name = "User name")]
public string UserName { get; set; }

 

       [HttpGet] // 只能用GET !!!        public ActionResult CheckUserNameExists(string UserName)  //遠程驗證UserName是否重複        {            DataEntities ef = new DataEntities(); //執行個體化EF            var itemtitle = ef.users.Where(c => c.username == UserName);            bool exists = itemtitle.Count() < 1 == false;            return Json(!exists, JsonRequestBehavior.AllowGet);        }

  本身來說這兩者都是很好,很強大, 但當他們在一起的時候,蛋疼的事情就來了,這樣無論如何都擷取不到Remote.細細地檢查幾遍都沒有發現問題,後來才想到了在MVC 4中預設的AccountController中所有的Action都加上了Authorize的原因. 於是在上述CheckUserNameExists的Action中也加上AllowAnonymous. 終於搞定了.

  在編程中總會遇到這樣那樣令人蛋疼的事,不過只要堅持下去,相信很快就不疼了.

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.