dir.by  
  Поиск  
Компьютер, программы
ASP.NET MVC (web сайт на архитектуре Model-View-Controller)
Writing the appendix "Planning tasks" in the MVC ASP.NET
 Аутентификация (login/register/logout) в приложении "Планирование дел, задач" | ASP.NET MVC | Visual Studio 2017 
посмотрели 10309 раз
обновлено: 15 January 2019
Шаг 1. В web.config включаем аутентификацию форм
Внутри секции <system.web> добавим
<authentication mode="Forms">
     <forms name="cookies" timeout="2880" loginUrl="~/Authentication/Login" ></forms>
</authentication>
  Файл web.config
<?xml version="1.0" encoding="utf-8"?>
<!--
     For more information on how to configure your ASP.NET application, please visit
     https://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" />
     </appSettings>
     <system.web>
          <compilation debug="true" targetFramework="4.6.1" />
          <httpRuntime targetFramework="4.6.1" />
          <authentication mode="Forms">
               <forms name="cookies" timeout="2880" loginUrl="~/Authentication/Login" ></forms>
          </authentication>
     </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.4.0" newVersion="5.2.4.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=2.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:default /nowarn:1659;1699;1701" />
               <compiler language="vb;vbs;visualbasic;vbscript" extension=".vb" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.VBCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:default /nowarn:41008 /define:_MYTYPE=\"Web\" /optionInfer+" />
          </compilers>
     </system.codedom>

     <connectionStrings>
          <add name="MyConnection1" connectionString="Data Source=EVGEN\SQLEXPRESS;Initial Catalog=MyDatabase1;Integrated Security=True;" providerName="System.Data.SqlClient" />
     </connectionStrings>

     <entityFramework>
          <defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework" />
          <providers>
               <provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
          </providers>
     </entityFramework>
</configuration>
Шаг 2. Добавим файл UserContext.cs в папку Models (класс User и класс UserContext для работы с Базой данных)
Нажмем правой клавишей мыши на папку "Models"AddNew Item
  C#     В файле UserContext.cs напишем код
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.Entity;

namespace Plan.Models
{
     public class UserContext : DbContext
     {
          // MyConnection1 это соединение с базой данных описанное в файле web.config
          public UserContext() : base("MyConnection1")
          {
          }

          public DbSet<User> Users { get; set; }
     }

     public class User
     {
          public int Id { get; set; }
          public string Email { get; set; }
          public string Password { get; set; }
     }
}
Шаг 3. Добавим файл UserLoginRegister.cs в папку Models (класс UserLogin и класс UserRegister)
При логине в форме мы будем использовать
класс UserLogin

При регистрации в форме мы будем использовать
класс UserRegister

Добавим файл UserLoginRegister.cs в папку Models
  C#     В файле UserLoginRegister.cs напишем код
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;

namespace Plan.Models
{
     public class UserLogin
     {
          [Required]
          public string Name { get; set; }

          [Required]
          [DataType(DataType.Password)]
          public string Password { get; set; }
     }

     public class UserRegister
     {
          [Required]
          public string Name { get; set; }

          [Required]
          [DataType(DataType.Password)]
          public string Password { get; set; }

          [Required]
          [DataType(DataType.Password)]
          [Compare("Password", ErrorMessage = "Пароли не совпадают")]
          public string ConfirmPassword { get; set; }

          [Required]
          public int Age { get; set; }
     }
}
Шаг 4. Добавляем AuthenticationController
Чтобы добавить контроллер в наш проект в окне Solution Explorer нажимаем правой клавишей мыши на
ControllersAddController
  C#     В файле AuthenticationController.cs напишем код
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
using Plan.Models;

namespace Plan.Controllers
{
     public class AuthenticationController : Controller
     {
          public ActionResult Login()
          {
               return View();
          }

          [HttpPost]
          [ValidateAntiForgeryToken]
          public ActionResult Login(UserLogin model)
          {
               if (ModelState.IsValid)
               {
                    // поиск пользователя в базе данных
                    User user = null;
                    using (UserContext db = new UserContext())
                    {
                         user = db.Users.FirstOrDefault(u => u.Email == model.Name && u.Password == model.Password);
                    }

                    // нашли пользователя
                    if (user != null)
                    {
                         // устанавливаем cookie
                         FormsAuthentication.SetAuthCookie(model.Name, true);

                         // переходим
                         return RedirectToAction("Index", "Home");
                    }
                    else
                    {
                         // выводим ошибку
                         ModelState.AddModelError("", "Пользователя с таким логином и паролем нет");
                    }
               }

               return View(model);
          }

          public ActionResult Register()
          {
               return View();
          }

          [HttpPost]
          [ValidateAntiForgeryToken]
          public ActionResult Register(UserRegister model)
          {
               if (ModelState.IsValid)
               {
                    // ищем пользователя в базе данных
                    User user = null;
                    using (UserContext db = new UserContext())
                    {
                         user = db.Users.FirstOrDefault(u => u.Email == model.Name);
                    }

                    // пользователя нет базе данных
                    if (user == null)
                    {
                         // создаем нового пользователя
                         using (UserContext db = new UserContext())
                         {
                              db.Users.Add(new User { Email = model.Name, Password = model.Password});
                              db.SaveChanges();

                              user = db.Users.Where(u => u.Email == model.Name && u.Password == model.Password).FirstOrDefault();
                         }

                         // пользователь добавлен в базу данных
                         if (user != null)
                         {
                              // устанавливаем cookie
                              FormsAuthentication.SetAuthCookie(model.Name, true);

                              // переходим
                              return RedirectToAction("Index", "Home");
                         }
                    }
                    else
                    {
                         // выводим ошибку
                         ModelState.AddModelError("", "Пользователь с таким логином уже существует");
                    }
               }

               return View(model);
          }

          public ActionResult Logoff()
          {
               FormsAuthentication.SignOut();
               return RedirectToAction("Index", "Home");
          }
     }
}
Шаг 5. Добавляем View с названием Login
Нажимаем правой клавишей мыши по методу Login в файле AuthenticationController.cs и нажимаем на Add View ...
  В файле Login.cshtml напишем код
@model Plan.Models.UserLogin

<!DOCTYPE html>

<html>
<head>
     <meta name="viewport" content="width=device-width" />
     <title>Вход</title>
</head>

<body>

     <!-- подключаем файлы Bootstrap -->
     <link href='@Url.Content("~/Content/bootstrap.min.css")' rel="stylesheet" type="text/css" />
     <script src='@Url.Content("~/Scripts/bootstrap.min.js")'></script>

     @using (Html.BeginForm())
     {
          @Html.AntiForgeryToken()

          <div class="pl-4">
               @Html.ValidationSummary(true)

               <!-- заголовок -->
               <div class="form-group">
                    <h2>Вход</h2>
               </div>

               <!-- login -->
               <div class="form-group">
                    @Html.LabelFor(model => model.Name, new { @class = "control-label" })
                    <div>
                         @Html.EditorFor(model => model.Name, new { @class = "form-control" })
                         @Html.ValidationMessageFor(model => model.Name)
                    </div>
               </div>

               <!-- password -->
               <div class="form-group">
                    @Html.LabelFor(model => model.Password, new { @class = "control-label" })
                    <div>
                         @Html.EditorFor(model => model.Password, new { @class = "form-control" })
                         @Html.ValidationMessageFor(model => model.Password)
                    </div>
               </div>

               <!-- Войти -->
               <div class="form-group">
                    <input type="submit" value="Войти" class="btn btn-info" />
               </div>
          </div>
     }

</body>
</html>
Шаг 6. Добавляем View с названием Register
Нажимаем правой клавишей мыши по методу Register в файле AuthenticationController.cs и нажимаем на Add View ...
  В файле Register.cshtml напишем код
@model Plan.Models.UserRegister

<!DOCTYPE html>

<html>
<head>
     <meta name="viewport" content="width=device-width" />
     <title>Регистрация</title>
</head>

<body>

     <!-- подключаем файлы Bootstrap -->
     <link href='@Url.Content("~/Content/bootstrap.min.css")' rel="stylesheet" type="text/css" />
     <script src='@Url.Content("~/Scripts/bootstrap.min.js")'></script>

     @using (Html.BeginForm())
     {
          @Html.AntiForgeryToken()

          <div class="pl-4">
               @Html.ValidationSummary(true)

               <!-- Заголовок -->
               <div class="form-group">
                    <h2>Регистрация</h2>
               </div>

               <!-- login -->
               <div class="form-group">
                    @Html.LabelFor(model => model.Name, new { @class = "control-label" })
                    <div>
                         @Html.EditorFor(model => model.Name, new { @class = "form-control" })
                         @Html.ValidationMessageFor(model => model.Name)
                    </div>
               </div>

               <!-- password -->
               <div class="form-group">
                    @Html.LabelFor(model => model.Password, new { @class = "control-label" })
                    <div>
                         @Html.EditorFor(model => model.Password, new { @class = "form-control" })
                         @Html.ValidationMessageFor(model => model.Password)
                    </div>
               </div>

               <!-- confirm password -->
               <div class="form-group">
                    @Html.LabelFor(model => model.ConfirmPassword, new { @class = "control-label" })
                    <div>
                         @Html.EditorFor(model => model.ConfirmPassword, new { @class = "form-control" })
                         @Html.ValidationMessageFor(model => model.ConfirmPassword)
                    </div>
               </div>

               <!-- Сохранить -->
               <div class="form-group">
                    <input type="submit" value="Сохранить" class="btn btn-info" />
               </div>
          </div>
     }

</body>
</html>
Шаг 7. В файле Views/MasterTemplate.cshtml напишем код
  cshtml  
@{
     Layout = null;
}

@{
     // переменные чтобы выставить активность или не активность в кнопках меню
     string MenuActiveList = "active";
     string MenuActiveReport = "";
     string MenuActiveChange = "";

     int ImgVersionToRefresh = 8;
}

<!DOCTYPE html>

<html>
<head>
     <meta name="viewport" content="width=device-width" />
     <title>MasterTemplate</title>
</head>

<body>
     <!-- подключаем файлы jQuery -->
     <script src='@Url.Content("~/Scripts/jquery-3.0.0.min.js")'></script>

     <!-- подключаем файлы Bootstrap -->
     <link href='@Url.Content("~/Content/bootstrap.min.css")' rel="stylesheet" type="text/css" />
     <script src='@Url.Content("~/Scripts/bootstrap.min.js")'></script>
    
     <!-- HTML элементы -->
     <div class="container">

          <div class="row">

               <div class="col-md-12" style="">

                    <!-- верхнее меню1 -->
                    <nav class="navbar navbar-expand-sm bg-light navbar-light">

                         <ul class="navbar-nav mr-auto">
                              <li class="nav-item">
                                   @Html.Label("Планирование дел, задач", new { @class = "" })
                              </li>
                         </ul>

                         <!-- кнопки в меню "Выйти", "Войти", "Регистрация" -->
                         <!-- Эти кнопки с правой стороны потому что в предыдущем ul стоит class='... mr-auto' -->
                         <ul class="navbar-nav">

                              <!-- проверяем пользователь залогинен? -->
                              @if (User.Identity.IsAuthenticated)
                              {
                                   <!-- имя пользователя -->
                                   <li class="nav-item">
                                        <span class="navbar-text">
                                             [ @User.Identity.Name ]
                                        </span>
                                   </li>

                                   <!-- кнопка 'Выйти' -->
                                   <li class="nav-item">
                                        <a class="nav-link" href='@Url.Action("Logoff", "Authentication")'> Выйти... </a>
                                   </li>
                              }

                              else
                              {
                                   <!-- кнопка 'Войти' -->
                                   <li class="nav-item">
                                        <a class="nav-link" href='@Url.Action("Login", "Authentication")'> Войти... </a>
                                   </li>

                                   <!-- мой разделитель -->
                                   <li class="nav-item">
                                        <span class="navbar-text">
                                             |
                                        </span>
                                   </li>

                                   <!-- Регистрация -->
                                   <li class="nav-item">
                                        <a class="nav-link" href='@Url.Action("Register", "Authentication")'> Регистрация... </a>
                                   </li>
                              }
                         </ul>
                    </nav>
               </div>
          </div>

          <div class="row">

               <div class="col-md-12" style="min-height:600px; padding-left:0px; padding-right:0px; border:3px solid gray; background-repeat:repeat-y; background-image:url(@Url.Content("~/Content/Images/PageBorder.png?version=" + ImgVersionToRefresh));">

                    <!-- верхнее меню2 -->
                    <nav class="navbar navbar-expand-sm bg-info navbar-info">

                         <!-- кнопки в меню "Список дел", "Отчеты", "Управление (поменять, добавить, удалить)" -->
                         <ul class="navbar-nav mr-auto">
                              <!-- кнопка "Список дел" -->
                              <li class="nav-item ml-5">
                                   <a class="btn btn-info @MenuActiveList" href='@Url.Action("Index")'>Список дел</a>
                              </li>

                              <!-- кнопка "Отчеты" -->
                              <li class="nav-item ml-5">
                                   <a class="btn btn-info @MenuActiveReport" href='@Url.Action("Report")'>Отчеты</a>
                              </li>

                              <!-- кнопка "Управление" -->
                              <li class="nav-item ml-5">
                                   <a class="btn btn-info @MenuActiveChange" href='@Url.Action("Change")'>Управление (поменять, добавить, удалить)</a>
                              </li>
                         </ul>
                    </nav>

                    <!-- тут вставится содержимое обычного представления -->
                    <div style="padding-left:60px; padding-top:20px;">
                         @RenderBody()
                    </div>
               </div>

          </div>
     </div>
</body>
</html>
Шаг 8. Запустим ASP.NET MVC приложение
Нажимаем Регистрация
При входе вводим логин и пароль
Когда вошли, мы видим имя залогиненного пользователя.
 
← Previous topic
Add the Entity Framework library and create a connection to the Database in the application "Planning tasks" | ASP.NET MVC | Visual Studio 2017
 
Next topic →
Add the class "Task" to save tasks, tasks to the database in the application "Planning tasks, tasks" | ASP.NET MVC | Visual Studio 2017
 
Your feedback ... Comments ...
   
Your Name
Your comment (www links can only be added by a logged-in user)

 
What is MVC in ASP.NET ?
Creating a new application ASP.NET MVC
Controller
Pass the data from the controller to the view in the MVC ASP.NET. Using ViewBag, ViewData, TempData, Model (strongly typed view)
View
What are Razor View and Operators in MVC ASP.NET
Create a variable and display it in View in the MVC ASP.NET
@using inside View in the MVC ASP.NET
@foreach(var item in arr) {...} inside the View in the MVC ASP.NET
@DateTime.Now inside the View in the MVC ASP.NET
How to find the name of the controller inside the View in the MVC ASP.NET
Display [DateTime | Date only | Time only] in the desired format in the MVC ASP.NET
Views
Strongly-typed-view in MVC ASP.NET
...
Master View using @RenderBody() in the MVC ASP.NET
Master View using @RenderBody() and additional sections @RenderSection in the MVC ASP.NET
...
Partial View in the MVC ASP.NET. Embed a partial representation @Html.Partial("My1") and @{ Html.RenderPartial("My1");}
When you click submit inside the partial view, the controller method is called ajax. The controller method should return PartialView(model) | ASP.NET MVC
...
Strongly-typed partial view in the MVC ASP.NET
Create the ViewModels folder. This is a good programming style for transferring data from the Controller to the View
Create the ViewModels folder. Create your class in the ViewModels folder. This is a good programming style for transferring data from the Controller to the View. Web Application ASP.NET MVC
Attributes. Use the attributes in the ViewModels (to show the combo buttons in the view). Using attributes in the Controller (to improve methods)
Attribute [Display(Name = "... ")] is described in the C# class and used in @Html.LabelFor, @Html.DisplayNameFor in the MVC ASP.NET
The attribute [Required(ErrorMessage = "Please enter a name")] is described for a property in the C# class and requires the property to be populated if the ErrorMessage error in the MVC ASP.NET is not filled in the screen
The attribute [Remote("IsValidAuthor", "Home", ErrorMessage = "Enter correct author of book")] is described for a property in a C# class and checks that property for correctness on the server via the IsValidAuthor method in conroller Home, if the method returns false, then there will be an ErrorMessage error on the screen in the MVC ASP.NET
The [HiddenInput(DisplayValue=false)] attribute is described in the C# class and is used in @Html.HiddenFor in the MVC ASP.NET
Routing
Links and redirects in the view
@Html.ActionLink inside the View in the MVC ASP.NET
@Html.RouteLink inside the View in the MVC ASP.NET
@Url.Action inside the View in the MVC ASP.NET
@Url.RouteUrl inside the View in the MVC ASP.NET
@Url.Content inside the View in the MVC ASP.NET
Bootstrap in MVC
Add and include Bootstrap (css, js files) to ASP.NET MVC project
JQuery in MVC
Connecting JQuery to ASP.NET MVC project
Using JQuery, we get the contents of the View in the MVC ASP.NET. Example: $.get("/Home/Index", function (data) {...}) ...
MVC AjaxExtensions class (asynchronous data retrieval)
Plugging jQuery & AJAX into ASP.NET MVC project
Using Ajax.ActionLink, get the contents of the View and insert it into the div in the MVC ASP.NET
Ajax object (this is the AjaxExtensions class) in MVC ASP.NET
Database (Entity Framework) in MVC ASP.NET
Entity Framework in the ASP.NET MVC application. Using Code First (we write c# code, and the tables in the database are created by ourselves)
Authentication (login/register/logout)
What is authentication (login/register/logout) in the MVC ASP.NET?
Example: Authentication (login/register/logout) in MVC ASP.NET using FormsAuthentication.SetAuthCookie(model. Name, true);
Authorization (admin/user/...)
What is authorization (admin/user/...) in the MVC ASP.NET?
Example: Authorization (admin/user/...) in MVC ASP.NET using the RoleProvider role provider
Writing the appendix "Planning tasks" in the MVC ASP.NET
Creating an empty application "Planning tasks, tasks" | ASP.NET MVC | Visual Studio 2017
Adding Bootstrap & jQuery libraries to the application "Scheduling tasks" | ASP.NET MVC | Visual Studio 2017
Create a master view (main menu & button login using Bootstrap) in the application "Planning tasks" | ASP.NET MVC | Visual Studio 2017
Add the "Home" controller and the "Index" view (the main page in the application "Planning tasks, tasks" | ASP.NET MVC | Visual Studio 2017
Add the Entity Framework library and create a connection to the Database in the application "Planning tasks" | ASP.NET MVC | Visual Studio 2017
Authentication (login/register/logout) in the application "Scheduling tasks" | ASP.NET MVC | Visual Studio 2017
Add the class "Task" to save tasks, tasks to the database in the application "Planning tasks, tasks" | ASP.NET MVC | Visual Studio 2017
Adding nUnit in the application "Planning tasks, tasks" | ASP.NET MVC | Visual Studio 2017
Additional topics, questions
Why is MVC ASP.NET better ASP.NET Web Forms?
Choosing between ASP.NET Core and ASP.NET?
How to choose an Internet browser to run a .NET project in it
How do I find the local address and port of your ASP.NET MVC application?
Scriptsindex.d.ts(8,1): error TS1008: Build:Unexpected token; "module, class, interface, enum, import or statement" expected. Scriptsindex.d.ts(8,13): error TS1005: Build:";" expected. in Visual Studio 2017 in the ASP.NET MVC app
Error "unable to connect to web server "iis express" | ASP.NET MVC | Visual Studio 2017
Error "This site can"t be reached" when run ASP.NET application | Solution: Recreate the Self-Signed HTTPS Certificate for localhost in IIS Express
WWW Sites to Learn ASP.NET MVC
Sites to learn ASP.NET MVC

  Ваши вопросы присылайте по почте: info@dir.by