ClientApp init

This commit is contained in:
shadowik 2023-05-16 20:05:59 +04:00
parent 48abf8eb93
commit 8ad04498d1
13 changed files with 309 additions and 53 deletions

View File

@ -0,0 +1,55 @@
using BankYouBankruptContracts.ViewModels;
using Newtonsoft.Json;
using System.Net.Http.Headers;
using System.Text;
namespace BankYouBankruptСlientApp
{
public class APIClient
{
private static readonly HttpClient _client = new();
public static ClientViewModel? Client { get; set; } = null;
public static void Connect(IConfiguration configuration)
{
_client.BaseAddress = new Uri(configuration["IPAddress"]);
_client.DefaultRequestHeaders.Accept.Clear();
_client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
}
//Get-запрос
public static T? GetRequest<T>(string requestUrl)
{
var response = _client.GetAsync(requestUrl);
var result = response.Result.Content.ReadAsStringAsync().Result;
if (response.Result.IsSuccessStatusCode)
{
return JsonConvert.DeserializeObject<T>(result);
}
else
{
throw new Exception(result);
}
return JsonConvert.DeserializeObject<T>("");
}
//Post-запрос
public static void PostRequest<T>(string requestUrl, T model)
{
var json = JsonConvert.SerializeObject(model);
var data = new StringContent(json, Encoding.UTF8, "application/json");
var response = _client.PostAsync(requestUrl, data);
var result = response.Result.Content.ReadAsStringAsync().Result;
if (!response.Result.IsSuccessStatusCode)
{
throw new Exception(result);
}
}
}
}

View File

@ -6,4 +6,12 @@
<ImplicitUsings>enable</ImplicitUsings> <ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup> </PropertyGroup>
<ItemGroup>
<PackageReference Include="Newtonsoft.Json" Version="13.0.3" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\BankYouBankruptContracts\BankYouBankruptContracts.csproj" />
</ItemGroup>
</Project> </Project>

View File

@ -1,6 +1,11 @@
using BankYouBankruptClientApp.Models; 
using BankYouBankruptClientApp.Models;
using BankYouBankruptContracts.BindingModels;
using BankYouBankruptContracts.ViewModels;
using BankYouBankruptСlientApp;
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc;
using System.Diagnostics; using System.Diagnostics;
using System.Xml.Linq;
namespace BankYouBankruptClientApp.Controllers namespace BankYouBankruptClientApp.Controllers
{ {
@ -13,20 +18,86 @@ namespace BankYouBankruptClientApp.Controllers
_logger = logger; _logger = logger;
} }
//вытаскивает через API клиента Get-запросом список его собственных заказов
[HttpGet]
public IActionResult Index() public IActionResult Index()
{ {
return View(); if (APIClient.Client == null)
{
return Redirect("~/Home/Enter");
} }
public IActionResult Privacy() return View(APIClient.GetRequest<ClientViewModel>($"api/Client/GetClient?clientId={APIClient.Client.Id}"));
{
return View();
} }
[ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)] [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
public IActionResult Error() public IActionResult Error()
{ {
return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier }); return View(new ErrorViewModel
{
RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier
});
}
//просто открытие вьюхи
[HttpGet]
public IActionResult Enter()
{
return View();
}
//отсылаем указанные данные на проверку
[HttpPost]
public void Enter(string login, string password)
{
if (string.IsNullOrEmpty(login) || string.IsNullOrEmpty(password))
{
throw new Exception("Введите логин и пароль");
}
APIClient.Client = APIClient.GetRequest<ClientViewModel>($"api/Client/Login?login={login}&password={password}");
if (APIClient.Client == null)
{
throw new Exception("Неверный логин/пароль");
}
Response.Redirect("Index");
}
//просто открытие вьюхи
[HttpGet]
public IActionResult Register()
{
return View();
}
//Post-запрос по созданию нового пользователя
[HttpPost]
public void Register(string login, string password, string name, string surname, string patronymic, string telephone)
{
if (string.IsNullOrEmpty(login) || string.IsNullOrEmpty(password) || string.IsNullOrEmpty(name)
|| string.IsNullOrEmpty(surname) || string.IsNullOrEmpty(patronymic) || string.IsNullOrEmpty(telephone))
{
throw new Exception("Введите логин, пароль, ФИО и телефон");
}
APIClient.PostRequest("api/Client/Register", new ClientBindingModel
{
Name = name,
Surname = surname,
Patronymic = patronymic,
Email = login,
Password = password,
Telephone = telephone
});
//переход на вкладку "Enter", чтобы пользователь сразу смог зайти
Response.Redirect("Enter");
return;
} }
} }
} }

View File

@ -1,3 +1,5 @@
using BankYouBankruptÑlientApp;
var builder = WebApplication.CreateBuilder(args); var builder = WebApplication.CreateBuilder(args);
// Add services to the container. // Add services to the container.
@ -5,6 +7,8 @@ builder.Services.AddControllersWithViews();
var app = builder.Build(); var app = builder.Build();
APIClient.Connect(builder.Configuration);
// Configure the HTTP request pipeline. // Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment()) if (!app.Environment.IsDevelopment())
{ {

View File

@ -0,0 +1,27 @@
@{
ViewData["Title"] = "Enter";
}
<div class="text-center">
<h2 class="display-4">Вход в приложение</h2>
</div>
<form method="post">
<div class="row">
<div class="col-4">Логин:</div>
<div class="col-8">
<input type="text" name="login" /
</div>
</div>
<div class="row">
<div class="col-4">Пароль:</div>
<div class="col-8">
<input type="password" name="password" />
</div>
</div>
<div class="row">
<div class="col-8"></div>
<div class="col-4">
<input type="submit" value="Вход" class="btn btn-primary" />
</div>
</div>
</form>

View File

@ -1,8 +1,26 @@
@{ @using BankYouBankruptContracts.ViewModels
@model ClientViewModel
@{
ViewData["Title"] = "Home Page"; ViewData["Title"] = "Home Page";
} }
<div class="text-center"> <div class="text-center">
<h1 class="display-4">Welcome</h1> <h1 class="display-4">Страница пользователя</h1>
<p>Learn about <a href="https://docs.microsoft.com/aspnet/core">building Web apps with ASP.NET Core</a>.</p> </div>
<div class="text-center">
@{
if (Model == null)
{
<h3 class="display-4">Сначала авторизируйтесь</h3>
return;
}
<p>Здравствуйтe, @Model.Name @Model.Patronymic</p>
<p>
<a asp-action="Create">Открыть счёт</a>
</p>
}
</div> </div>

View File

@ -1,6 +0,0 @@
@{
ViewData["Title"] = "Privacy Policy";
}
<h1>@ViewData["Title"]</h1>
<p>Use this page to detail your site's privacy policy.</p>

View File

@ -0,0 +1,51 @@
@{
ViewData["Title"] = "Register";
}
<div class="text-center">
<h2 class="display-4">Регистрация</h2>
</div>
<form method="post">
<div class="row">
<div class="col-4">Логин:</div>
<div class="col-8">
<input type="text" name="login" />
</div>
</div>
<div class="row">
<div class="col-4">Пароль:</div>
<div class="col-8">
<input type="password" name="password" />
</div>
</div>
<div class="row">
<div class="col-4">Имя:</div>
<div class="col-8">
<input type="text" name="name" />
</div>
</div>
<div class="row">
<div class="col-4">Фамилия:</div>
<div class="col-8">
<input type="text" name="surname" />
</div>
</div>
<div class="row">
<div class="col-4">Отчество:</div>
<div class="col-8">
<input type="text" name="patronymic" />
</div>
</div>
<div class="row">
<div class="col-4">Телефон:</div>
<div class="col-8">
<input type="text" name="telephone" />
</div>
</div>
<div class="row">
<div class="col-8"></div>
<div class="col-4">
<input type="submit" value="Регистрация" class="btn btn-primary" />
</div>
</div>
</form>

View File

@ -5,25 +5,37 @@
<meta name="viewport" content="width=device-width, initial-scale=1.0" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>@ViewData["Title"] - BankYouBankruptClientApp</title> <title>@ViewData["Title"] - BankYouBankruptClientApp</title>
<link rel="stylesheet" href="~/lib/bootstrap/dist/css/bootstrap.min.css" /> <link rel="stylesheet" href="~/lib/bootstrap/dist/css/bootstrap.min.css" />
<link rel="stylesheet" href="~/css/site.css" asp-append-version="true" /> <link rel="stylesheet" href="~/css/site.css" />
<link rel="stylesheet" href="~/BankYouBankruptClientApp.styles.css" asp-append-version="true" /> <script src="~/lib/jquery/dist/jquery.min.js"></script>
<script src="~/lib/bootstrap/dist/js/bootstrap.bundle.min.js"></script>
</head> </head>
<body> <body>
<header> <header>
<nav class="navbar navbar-expand-sm navbar-toggleable-sm navbar-light bg-white border-bottom box-shadow mb-3"> <nav class="navbar navbar-expand-sm navbar-toggleable-sm navbar-light bg-white border-bottom box-shadow mb-3">
<div class="container-fluid"> <div class="container">
<a class="navbar-brand" asp-area="" asp-controller="Home" asp-action="Index">BankYouBankruptClientApp</a> <a class="navbar-brand" asp-area="" asp-controller="Home" aspaction="Index">
<button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target=".navbar-collapse" aria-controls="navbarSupportedContent" Банк "Вы банкрот"
</a>
<button class="navbar-toggler" type="button" datatoggle="collapse" data-target=".navbar-collapse" ariacontrols="navbarSupportedContent"
aria-expanded="false" aria-label="Toggle navigation"> aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span> <span class="navbar-toggler-icon"></span>
</button> </button>
<div class="navbar-collapse collapse d-sm-inline-flex justify-content-between"> <div class="navbar-collapse collapse d-sm-inline-flex flex-smrow-reverse">
<ul class="navbar-nav flex-grow-1"> <ul class="navbar-nav flex-grow-1">
<li class="nav-item"> <li class="nav-item">
<a class="nav-link text-dark" asp-area="" asp-controller="Home" asp-action="Index">Home</a> <a class="nav-link text-dark" asparea="" asp-controller="Home" asp-action="Index">Счета</a>
</li> </li>
<li class="nav-item"> <li class="nav-item">
<a class="nav-link text-dark" asp-area="" asp-controller="Home" asp-action="Privacy">Privacy</a> <a class="nav-link text-dark" asparea="" asp-controller="Home" asp-action="CreateReport">Отчёт</a>
</li>
<li class="nav-item">
<a class="nav-link text-dark" asparea="" asp-controller="Home" asp-action="Privacy">Личные данные</a>
</li>
<li class="nav-item">
<a class="nav-link text-dark" asparea="" asp-controller="Home" asp-action="Enter">Вход</a>
</li>
<li class="nav-item">
<a class="nav-link text-dark" asparea="" asp-controller="Home" asp-action="Register">Регистрация</a>
</li> </li>
</ul> </ul>
</div> </div>
@ -38,7 +50,7 @@
<footer class="border-top footer text-muted"> <footer class="border-top footer text-muted">
<div class="container"> <div class="container">
&copy; 2023 - BankYouBankruptClientApp - <a asp-area="" asp-controller="Home" asp-action="Privacy">Privacy</a> &copy; 2023 - BankYouBankruptCashierApp - <a asp-area="" asp-controller="Home" asp-action="Privacy">Личные данные</a>
</div> </div>
</footer> </footer>
<script src="~/lib/jquery/dist/jquery.min.js"></script> <script src="~/lib/jquery/dist/jquery.min.js"></script>

View File

@ -26,6 +26,7 @@ a {
.border-top { .border-top {
border-top: 1px solid #e5e5e5; border-top: 1px solid #e5e5e5;
} }
.border-bottom { .border-bottom {
border-bottom: 1px solid #e5e5e5; border-bottom: 1px solid #e5e5e5;
} }

View File

@ -5,5 +5,6 @@
"Microsoft.AspNetCore": "Warning" "Microsoft.AspNetCore": "Warning"
} }
}, },
"AllowedHosts": "*" "AllowedHosts": "*",
"IPAddress": "http://localhost:5179/"
} }

View File

@ -15,8 +15,8 @@ namespace BankYouBankruptDatabaseImplement
{ {
if (!optionsBuilder.IsConfigured) if (!optionsBuilder.IsConfigured)
{ {
//optionsBuilder.UseSqlServer(@"Data Source=SHADOWIK\SHADOWIK;Initial Catalog=BankYouBankrupt;Integrated Security=True;TrustServerCertificate=True"); optionsBuilder.UseSqlServer(@"Data Source=SHADOWIK\SHADOWIK;Initial Catalog=BankYouBankrupt;Integrated Security=True;TrustServerCertificate=True");
optionsBuilder.UseSqlServer(@"Data Source=LAPTOP-CFLH20EE\SQLEXPRESS;Initial Catalog=BankYouBankrupt;Integrated Security=True;MultipleActiveResultSets=True;;TrustServerCertificate=True"); //optionsBuilder.UseSqlServer(@"Data Source=LAPTOP-CFLH20EE\SQLEXPRESS;Initial Catalog=BankYouBankrupt;Integrated Security=True;MultipleActiveResultSets=True;;TrustServerCertificate=True");
} }
base.OnConfiguring(optionsBuilder); base.OnConfiguring(optionsBuilder);
} }

View File

@ -55,6 +55,20 @@ namespace BankYouBankruptRestApi.Controllers
} }
} }
[HttpGet]
public ClientViewModel? GetClient(int clientId)
{
try
{
return _clientLogic.ReadElement(new ClientSearchModel { Id = clientId });
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка получения пользователя");
throw;
}
}
[HttpPost] [HttpPost]
public void Register(ClientBindingModel model) public void Register(ClientBindingModel model)
{ {