asp.net Forms 身份驗證 html頁面
阿新 • • 發佈:2019-01-26
IIS 中預設是不支援靜態頁面進行Forms驗證,在網上找個了好多答案,配置都太過繁瑣
想讓IIS的Forms驗證 支援HTML靜態頁面其實只需要在web.config下進行簡單的配置就可以了
1、在 system.web節點 配置 Forms驗證
2、在 configuration 節點下 增加 location節點 宣告需要驗證的檔案<system.web> <authentication mode="Forms"> <forms loginUrl="Web/login.html" timeout="100" protection="All" /> </authentication> </system.web>
<location path="Web/Views">
<system.web>
<authorization>
<deny users="?"/>
</authorization>
</system.web>
</location>
此時未登入的狀態下 訪問Views檔案下的aspx,cshtml等.net的資原始檔就會重定向至Web/login.html 頁面,但是訪問html、xml等檔案還是不需要驗證。3、在system.webServer節點增加 handlers 節點配置
name: 隨便定義,但是必須唯一<system.webServer> <handlers> <add name="htmlPageHandlerFactory" path="*.html" verb="*" type="System.Web.UI.PageHandlerFactory" resourceType="Unspecified" preCondition="integratedMode" /> </handlers> </system.webServer>
path :*表示匹配所有檔案,*.html 只匹配html檔案
verb 請求謂詞 get、post 。 *號表示支援所有謂詞
此時再次訪問站點的 html檔案就會出現如下圖的錯誤
提示已經很明顯,只需要在compilation節點下注冊一個.html的擴充套件
<system.web>
<authentication mode="Forms">
<forms loginUrl="Web/login.html" timeout="100" protection="All" />
</authentication>
<compilation debug="true" targetFramework="4.5" defaultLanguage="C#">
<buildProviders>
<add extension=".html" type="System.Web.Compilation.PageBuildProvider"/>
</buildProviders>
</compilation>
</system.web>
當然 最重要的一步不能忘記,登入成功之後設定憑證
[HttpGet]
public ActionResult Login()
{
System.Web.Security.FormsAuthentication.SetAuthCookie(Guid.NewGuid().ToString(), true);
return Json(new { result = true, msg = "登入成功" }, JsonRequestBehavior.AllowGet);
}