Мой источник:FormsAuthentication в ASP.NET MVC 4 не работает
Web.config
<?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>
<connectionStrings>
<add name="DefaultConnection" connectionString="Data Source=(LocalDb)\v11.0;AttachDbFilename=|DataDirectory|\aspnet-LogInSystem-20140901072022.mdf;Initial Catalog=aspnet-LogInSystem-20140901072022;Integrated Security=True" providerName="System.Data.SqlClient" />
<add name="MainDbContext" connectionString="metadata=res://*/MainDbModel.csdl|res://*/MainDbModel.ssdl|res://*/MainDbModel.msl;provider=System.Data.SqlClient;provider connection string="data source=(LocalDB)\v11.0;attachdbfilename=|DataDirectory|\MainDb.mdf;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework"" providerName="System.Data.EntityClient" />
</connectionStrings>
<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" />
</appSettings>
<system.web>
<authentication mode="None" />
<compilation debug="true" targetFramework="4.5" />
<httpRuntime targetFramework="4.5" />
</system.web>
<system.webServer>
<modules>
<remove name="FormsAuthenticationModule" />
</modules>
</system.webServer>
<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.Mvc" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="1.0.0.0-5.0.0.0" newVersion="5.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="WebGrease" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="0.0.0.0-1.5.2.14234" newVersion="1.5.2.14234" />
</dependentAssembly>
</assemblyBinding>
</runtime>
<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
<parameters>
<parameter value="v11.0" />
</parameters>
</defaultConnectionFactory>
<providers>
<provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
</providers>
</entityFramework>
</configuration>
Войти метод:
[HttpPost]
public ActionResult LogIn(UserModel user)
{
if (ModelState.IsValid)
{
if (IsValid(user.Email, user.Password))
{
System.Web.Security.FormsAuthentication.SetAuthCookie(user.Email, false);
return RedirectToAction("Index", "Home");
}
else
{
ModelState.AddModelError("", "Login data is incorrect.");
}
}
return View(user);
}
и код:
@if (Request.IsAuthenticated)
{
<strong>@Html.Encode(User.Identity.Name)</strong>
@Html.ActionLink("Log Out", "Logout", "User")
}
else
{
@Html.ActionLink("Register", "Register", "User")
<span> | </span>
@Html.ActionLink("Log in", "Login", "User")
}
@Edit LogIn:
@using (Html.BeginForm())
{
@Html.ValidationSummary(true, "Login failed. Check your login details")
<div>
<fieldset>
<legend>Login form</legend>
<div>@Html.LabelFor(u => u.Email)</div>
<div>
@Html.TextBoxFor(u=>u.Email)
@Html.ValidationMessageFor(u=>u.Email)
</div>
<div>@Html.LabelFor(u => u.Password)</div>
<div>
@Html.PasswordFor(u => u.Password)
@Html.ValidationMessageFor(u => u.Password)
</div>
<input type="submit" value="Log In"/>
</fieldset>
</div>
}
Затем я нажимаю кнопку logIn
(это не показывают в этом коде), то я иду: public ActionResult LogIn(UserModel user)
метод. Тогда у меня есть непросроченный и т.д ...
Следующий шаг: System.Web.Security.FormsAuthentication.SetAuthCookie(user.Email, false);
но когда страница обновляется, я не могу видеть мою user.Email
, но все время видеть Register | Log In
, но должно быть, f.e [email protected] | Log Out
. Он похож на: Request.IsAuthenticated == false
Как его разрешить?
Строго говоря, запрос не был идентифицирован, когда он прибыл, так что может быть, почему Request.IsAuthenticated является ложным. Что произойдет, если вы обновите страницу? Выполняется ли аутентификация запроса? – Rune
ничего не происходит:/все время я не вижу свое имя журнала после страницы обновления;/ – W92
Как будет выполняться аутентификация форм при ее включении с помощью ' '? –