简体   繁体   English

使用ASP.Net MVC5轻松登录

[英]Simple Login with ASP.Net MVC5

I have been trying to get my head around OWIN and Identity to get it play well with my Existing app. 我一直在努力使OWIN和Identity脱颖而出,以使其在我现有的应用程序中很好地发挥作用。 The application was coded in Plain ASP.Net and I want to port it to MVC to organize it better. 该应用程序是用Plain ASP.Net编码的,我想将其移植到MVC以更好地组织它。 The app have established database including Users table so using Identity table is not option. 该应用程序已经建立了包括Users表的数据库,因此不能选择使用Identity表。 The wall I hit with Identity is that it requires Email and my system is NOT supposed to demand user email. 我遇到Identity时遇到的麻烦是它需要Email,而我的系统不应要求用户使用Email。 After trying almost everything (days reading almost every answer on the subject) I have come to conclusion that it will take more time to get it done, and that brings me to my question. 在尝试了几乎所有内容之后(几天阅读了关于该主题的几乎所有答案),我得出的结论是,完成它将花费更多的时间,这使我提出了自己的问题。

Being PHP guy (jumped to ASP.Net not long ago) I could easily make a working login in 10minutes and now I need a thing like it, something like 作为PHP的家伙(不久前跳到ASP.Net),我可以轻松地在10分钟内进行有效的登录,现在我需要类似的东西,例如

$user = User::findByUserName($username); //somehow here I find user from database
if($user!=null)
{
    $_SESSION['isLoggedIn'] = true;
    $_SESSION['fullname'] = $user->fullName;
}
else
{
    //redirect to login with error
}

I cannot find a session class in MVC5. 我在MVC5中找不到会话类。 Is that even possible? 那有可能吗? If no, is there a simple route to solve my issue? 如果没有,有没有简单的方法可以解决我的问题?

The most common way to cache is to either place it in the 'Global' server cache or place it in the session. 缓存的最常见方法是将其放置在“全局”服务器缓存中或将其放置在会话中。 There are other ways to save state and I would recommend looking into alternatives as the techniques below use the System.Web namespace. 还有其他保存状态的方法,由于下面的技术使用System.Web命名空间,因此我建议您研究替代方法。 System.Web will not be included in MVC6 . System.Web将不包含在MVC6中

Global Cache 全局缓存

//Save User
System.Web.HttpContext.Current.Cache.Insert(
                       "CurrentUser", 
                        User, 
                        null, 
                        System.Web.Caching.Cache.NoAbsoluteExpiration, 
                        new TimeSpan(0,20,0), 
                        System.Web.Caching.CacheItemPriority.Normal, 
                        null);       
//Get User   
User user=(User)System.Web.HttpContext.Current.Cache["CurrentUser"];

Session Cache 会话缓存

//Save User   
HttpContext.Current.Session.Add("CurrentUser",User); 

//Get User
User=(User)HttpContext.Current.Session["CurrentUser"];

you could basically tell owin manuelly to authenticate the user without using the identity-stuff (i dont like it either, at least for small projects). 您基本上可以告诉owin手动认证用户,而无需使用身份信息(我也不喜欢,至少对于小型项目而言)。 Then you could easily use the default authorize anotation Heres a tutorial: OWIN AUTH 然后,您可以轻松地使用默认的授权注释。这是一个教程: OWIN AUTH

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM