• MVC简单用户登录授权认证


    1.控制器上面用 [Authorize] 属性标识,表示当前控制器内的所有函数需要用户认证才能访问

    2.函数上面用 [AllowAnonymous] 属性标识,表示当前函数不需要用户认证可以直接访问

    3.函数上面使用 [NonAction] 属性标识,表示此方法不作为控制器函数

    代码:

    1.HomeController

    namespace TestMVC.Controllers
    {
        [Authorize]
        public class HomeController : Controller
        {
            // GET: Home
            public ActionResult Index()
            {
                return View();
            }
            [AllowAnonymous]
            public ActionResult Login()
            {
                return View();
            }
            [AllowAnonymous]
            [HttpPost]
            public ActionResult DoLogin(UserDetail user)
            {
                if (IsValidUser(user))
                {
                    //注册账户
                    FormsAuthentication.SetAuthCookie(user.UserName, false);
                    return RedirectToAction("Index", "Home");
                }
                else {
                    //错误消息提示
                    ModelState.AddModelError("ErrorMessage", "用户名或密码错误!");
                    return View("Login");
                }
            }
            [NonAction]
            public bool IsValidUser(UserDetail user)
            {
                if (user.UserName == "admin" && user.Password == "admin")
                    return true;
                else
                    return false;
            }
        }
    }
    View Code

    2.Home/Index.cshtml

    @{
        Layout = null;
        
    }
    
    <!DOCTYPE html>
    
    <html>
    <head>
        <meta name="viewport" content="width=device-width" />
        <title>Index</title>
    </head>
    <body>
        <div> 
            <h1>首页</h1>
        </div>
        
    </body>
    </html>
    View Code

    3.Home/Login.cshtml

    @model TestMVC.Models.UserDetail
    @{
        Layout = null;
    }
    
    <!DOCTYPE html>
    
    <html>
    <head>
        <meta name="viewport" content="width=device-width" />
        <title>Login</title>
    </head>
    <body>
        <div> 
            @Html.ValidationMessage("ErrorMessage", new { style = "color:red;" })
            @using(Html.BeginForm("DoLogin","Home",FormMethod.Post)){
                @Html.LabelFor(u=>u.UserName)
                @Html.TextBoxFor(u=>u.UserName)
                <br />
                @Html.LabelFor(u => u.Password)
                @Html.TextBoxFor(u => u.Password)
                <br />
                <input type="submit" value="登录" />
            }
        </div>
    </body>
    </html>
    View Code

    4.Web.config配置,当验证登录没有通过时跳转的Home/Login页面

  • 相关阅读:
    HttpServletRequest和HttpServletResponse实例
    ioc autofac简单示例
    sql left join 字符串
    sqlserver split函数
    类型同时存在于A.dll和B.dll中的解决办法
    ef使用dbfirst方式连接mysql
    html5 图片上传 预览
    webservice使用EF生成的model序列化问题
    sqlserver2008数据库文件降级为sqlserver2005文件
    [转]webapi部署在IIS7.5报404的解决方案
  • 原文地址:https://www.cnblogs.com/myindex/p/5465014.html
Copyright © 2020-2023  润新知