首先新建一个BaseController,用于验证用户是否登录成功!
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace DocumentAssistant.Controllers
{
public class BaseController : Controller
{
protected override void OnActionExecuting(ActionExecutingContext filterContext)
{
if (!this.checkLogin())// 判断是否登录
{
filterContext.Result = RedirectToRoute("Default", new { Controller = "Login", Action = "Login" });
}
base.OnActionExecuting(filterContext);
}
/// <summary>
/// 判断是否登录
/// </summary>
protected bool checkLogin()
{
if (this.Session["User"] == null)
{
return false;
}
return true;
}
}
}
在其他的Controller中继承BaseControl
例如:
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using DocumentAssistant.Service;
using System.Net.Sockets;
using System.Net.Mail;
using System.Net;
using System.IO;
using System.Drawing;
using System.Drawing.Imaging;
using Newtonsoft.Json;
namespace Document.Controllers
{
public class DocumentController : BaseController
{
// GET: Document
public ActionResult Index()
{
return View();
}
}
}
login.cshtml
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title></title>
<link href="~/Content/AdminLTE/bower_components/bootstrap/dist/css/bootstrap.min.css" rel="stylesheet" />
<link href="~/Content/AdminLTE/dist/css/skins/skin-dark.css" rel="stylesheet" />
<script src="~/Scripts/jquery-1.10.2.js"></script>
<script type="text/javascript">
$(function () {
})
function Login() {
UserName = $('#txtUserName').val();
Pwd = $('#txtPassword').val();
var url = "/Login/CheckADUser?UserName=" + UserName + "&Pwd=" + Pwd ;
$.ajax({
url: url,
async: false,
type: "POST",
contentType: "application/json",
// data: param,
success: function (data) {
console.log(data);
if (data == 'Success') {
window.location.href = '/Document/DocumentAssistant';
} else {
alert('User Name or Password is Incorrect');
//window.location.href = '/Document/DocumentTemplate';
}
}
});
}
</script>
</head>
<body class="hold-transition skin-blue sidebar-mini"style="background-color:black">
<div class="content" style="color:black;background-color:transparent;">
<div class="row"> </div>
<div class="row"> </div>
<div class="row"> </div>
<div class="row"> </div>
<div class="row"> </div>
<div class="row"> </div>
<div class="row"> </div>
<div class="row"> </div>
<div class="row">
<div class="col-md-4">
</div>
<div class="col-md-3">
<div class="panel panel-primary" style="background-color:transparent;">
<div class="panel-heading">
<h3 class="panel-title">User Login</h3>
</div>
<div class="panel-body">
<div class="row">
<div class="col-md-1">
</div>
<div class="col-md-4">
<input type="text" id="txtUserName" value="" placeholder="UserName" />
</div>
</div>
<div class="row"> </div>
<div class="row">
<div class="col-md-1">
</div>
<div class="col-md-4">
<input type="password" id="txtPassword" value="" placeholder="Password" />
</div>
</div>
<div class="row"> </div>
<div class="row">
<div class="col-md-1">
</div>
<div class="col-md-4">
<button class="btn btn-primary " οnclick="Login()">Login</button>
</div>
<div class="col-md-4">
<button class="btn btn-primary ">Cancel</button>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</body>
</html>
LoginController.cs
using DocumentAssistant.Service;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace DocumentAssistant.Controllers
{
public class LoginController : Controller
{
// GET: Login
public ActionResult Index()
{
return View();
}
public ActionResult Login()
{
return View();
}
/// <summary>
/// 2018-03-07
/// </summary>
/// <param name="param"></param>
/// <returns></returns>
public JsonResult CheckADUser(string UserName,string Pwd)
{
LDAP ldap = new LDAP();
string ErrorMsg = "";
if (ldap.IsAuthenticated(UserName, Pwd))
{
ErrorMsg = "Success";
Session["User"] = UserName;
Session["EmployeeNo"] = DBAuthority.GetEmployeeNo(UserName);
}
else
{
ErrorMsg = "Fail";
Session["User"] = "";
Session["EmployeeNo"] = "";
}
//string js = JsonConvert.SerializeObject();
return Json(ErrorMsg);
}
}
}
设置Session失效时间
<?xml version="1.0" encoding="utf-8"?>
<!--
For more information on how to configure your ASP.NET application, please visit
http://go.microsoft.com/fwlink/?LinkId=301880
-->
<configuration>
<configSections>
<!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
</configSections>
<appSettings>
<add key="webpages:Version" value="3.0.0.0" />
<add key="webpages:Enabled" value="false" />
<add key="ClientValidationEnabled" value="true" />
<add key="UnobtrusiveJavaScriptEnabled" value="true" />
<add key="LDAPPath" value="LDAP://DC=asia,DC=AD,DC=company,DC=com" />
<add key="DomainDefault" value="asia.ad.company.com" />
<add key="ByPassADAuth" value="true" />
<add key="ByPassADAuthPwd" value="df" />
<add key="LoginUrl" value="~/Mobile/Login.aspx" />
</appSettings>
<!--<appSettings>
<add key="webpages:Enabled" value="false" />
</appSettings>-->
<!--<session-config>
<session-timeout>1</session-timeout>
</session-config>-->
<connectionStrings>
<add name="ConnectionString" connectionString="Data Source=127.0.0.1;Initial Catalog=DEVDB;User ID=user;Password=user" providerName="System.Data.SqlClient" />
</connectionStrings>
<system.web>
<sessionState mode="InProc" timeout="15"/>
<compilation debug="true" targetFramework="4.5.2" />
<httpRuntime targetFramework="4.5.2" />
<authentication mode="Windows" />
</system.web>
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="System.Web.Helpers" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Web.WebPages" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="1.0.0.0-5.2.3.0" newVersion="5.2.3.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="WebGrease" publicKeyToken="31bf3856ad364e35" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-1.5.2.14234" newVersion="1.5.2.14234" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="Newtonsoft.Json" publicKeyToken="30ad4fe6b2a6aeed" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-9.0.0.0" newVersion="9.0.0.0" />
</dependentAssembly>
</assemblyBinding>
</runtime>
<system.codedom>
<compilers>
<compiler language="c#;cs;csharp" extension=".cs" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:6 /nowarn:1659;1699;1701" />
<compiler language="vb;vbs;visualbasic;vbscript" extension=".vb" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.VBCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:14 /nowarn:41008 /define:_MYTYPE=\"Web\" /optionInfer+" />
</compilers>
</system.codedom>
<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
<parameters>
<parameter value="mssqllocaldb" />
</parameters>
</defaultConnectionFactory>
<providers>
<provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
</providers>
</entityFramework>
</configuration>
修改web.config 设置session失效