исправляем реквест

This commit is contained in:
Zara28 2024-09-26 11:04:52 +04:00
parent 37996c249a
commit 080625d270
26 changed files with 710 additions and 0 deletions

7
dozorova_alena_lab_3/.gitignore vendored Normal file
View File

@ -0,0 +1,7 @@
/dozorova_alena_lab_3/PostService/.vs
/dozorova_alena_lab_3/PostService/bin
/dozorova_alena_lab_3/PostService/obj
/dozorova_alena_lab_3/WorkerService/.vs
/dozorova_alena_lab_3/WorkerService/bin
/dozorova_alena_lab_3/WorkerService/obj

View File

@ -0,0 +1,30 @@
**/.classpath
**/.dockerignore
**/.env
**/.git
**/.gitignore
**/.project
**/.settings
**/.toolstarget
**/.vs
**/.vscode
**/*.*proj.user
**/*.dbmdl
**/*.jfm
**/azds.yaml
**/bin
**/charts
**/docker-compose*
**/Dockerfile*
**/node_modules
**/npm-debug.log
**/obj
**/secrets.dev.yaml
**/values.dev.yaml
LICENSE
README.md
!**/.gitignore
!.git/HEAD
!.git/config
!.git/packed-refs
!.git/refs/heads/**

View File

@ -0,0 +1,94 @@
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
namespace PostService.Controllers
{
[ApiController]
[Route("[controller]")]
public class HomeController : ControllerBase
{
private readonly ILogger<HomeController> _logger;
public static List<Post> list = new List<Post>()
{
new Post()
{
Id = Guid.NewGuid(),
Name = "Default"
}
};
public HomeController(ILogger<HomeController> logger)
{
_logger = logger;
}
[HttpGet("get")]
public IActionResult Get()
{
return list == null || list.Count == 0 ? NotFound() : Ok(list);
}
[HttpGet("get/{Id}")]
public IActionResult Get([FromRoute] Guid Id)
{
var obj = list.Where(l => l.Id == Id).FirstOrDefault();
return obj == null ? NotFound() : Ok(obj);
}
[HttpPost("create")]
public IActionResult Create([FromBody] CreateUpdatePost data)
{
try
{
var model = new Post()
{
Id = Guid.NewGuid(),
Name = data.Name,
};
list.Add(model);
var modelForResult = new CreateUpdatePost
{
Name = model.Name
};
return Ok(modelForResult);
}
catch (Exception ex)
{
return BadRequest(ex.Message);
}
}
[HttpPut("update/{Id}")]
public IActionResult Update([FromRoute] Guid Id,
[FromBody] CreateUpdatePost data)
{
var oldModel = list.Where(l => l.Id == Id).Select(l => list.IndexOf(l)).FirstOrDefault();
if (oldModel != null)
{
list[oldModel].Name = data.Name;
var modelForResult = new CreateUpdatePost {
Name = data.Name,
};
return Ok(modelForResult);
}
else return NotFound();
}
[HttpDelete("delete/{Id}")]
public IActionResult Delete([FromRoute] Guid Id)
{
var model = list.Where(l => l.Id != Id).FirstOrDefault();
if (model != null) {
list.Remove(model);
return Ok();
}
else return NotFound();
}
}
}

View File

@ -0,0 +1,24 @@
#See https://aka.ms/customizecontainer to learn how to customize your debug container and how Visual Studio uses this Dockerfile to build your images for faster debugging.
FROM mcr.microsoft.com/dotnet/aspnet:6.0 AS base
WORKDIR /app
EXPOSE 80
EXPOSE 443
FROM mcr.microsoft.com/dotnet/sdk:6.0 AS build
ARG BUILD_CONFIGURATION=Release
WORKDIR /src
COPY ["PostService.csproj", "."]
RUN dotnet restore "./PostService.csproj"
COPY . .
WORKDIR "/src/."
RUN dotnet build "./PostService.csproj" -c $BUILD_CONFIGURATION -o /app/build
FROM build AS publish
ARG BUILD_CONFIGURATION=Release
RUN dotnet publish "./PostService.csproj" -c $BUILD_CONFIGURATION -o /app/publish /p:UseAppHost=false
FROM base AS final
WORKDIR /app
COPY --from=publish /app/publish .
ENTRYPOINT ["dotnet", "PostService.dll"]

View File

@ -0,0 +1,16 @@
namespace PostService
{
public class Post
{
public Guid Id { get; set; }
public string Name { get; set; }
}
public class PostDTO : Post { }
public class CreateUpdatePost
{
public string Name { get; set; }
}
}

View File

@ -0,0 +1,18 @@
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<TargetFramework>net6.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
<UserSecretsId>1a8ae13d-1a3e-4308-955e-4fbf68b758c9</UserSecretsId>
<DockerDefaultTargetOS>Linux</DockerDefaultTargetOS>
<DockerfileContext>.</DockerfileContext>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.VisualStudio.Azure.Containers.Tools.Targets" Version="1.20.1" />
<PackageReference Include="Newtonsoft.Json" Version="13.0.3" />
<PackageReference Include="Swashbuckle.AspNetCore" Version="6.5.0" />
</ItemGroup>
</Project>

View File

@ -0,0 +1,9 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="Current" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<ActiveDebugProfile>PostService</ActiveDebugProfile>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|AnyCPU'">
<DebuggerFlavor>ProjectDebugger</DebuggerFlavor>
</PropertyGroup>
</Project>

View File

@ -0,0 +1,25 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 17
VisualStudioVersion = 17.10.35004.147
MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "PostService", "PostService.csproj", "{EB304D56-A05F-41BC-9523-B5FEB658BCEE}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{EB304D56-A05F-41BC-9523-B5FEB658BCEE}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{EB304D56-A05F-41BC-9523-B5FEB658BCEE}.Debug|Any CPU.Build.0 = Debug|Any CPU
{EB304D56-A05F-41BC-9523-B5FEB658BCEE}.Release|Any CPU.ActiveCfg = Release|Any CPU
{EB304D56-A05F-41BC-9523-B5FEB658BCEE}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {6625EB51-D403-4C57-A7C2-AA01C90AB472}
EndGlobalSection
EndGlobal

View File

@ -0,0 +1,31 @@
using Microsoft.OpenApi.Models;
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
var app = builder.Build();
app.UseSwagger(c =>
{
c.PreSerializeFilters.Add((swaggerDoc, httpReq) =>
{
swaggerDoc.Servers = new List<OpenApiServer> { new OpenApiServer { Url = $"{httpReq.Scheme}://{httpReq.Host.Value}/postservice" } };
});
});
app.UseSwaggerUI();
app.UseHttpsRedirection();
app.UseAuthorization();
app.MapControllers();
app.Run();

View File

@ -0,0 +1,41 @@
{
"profiles": {
"PostService": {
"commandName": "Project",
"launchBrowser": true,
"launchUrl": "swagger",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
},
"dotnetRunMessages": true,
"applicationUrl": "https://localhost:7293;http://localhost:5139"
},
"IIS Express": {
"commandName": "IISExpress",
"launchBrowser": true,
"launchUrl": "swagger",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
},
"Container (Dockerfile)": {
"commandName": "Docker",
"launchBrowser": true,
"launchUrl": "{Scheme}://{ServiceHost}:{ServicePort}/swagger",
"environmentVariables": {
"ASPNETCORE_URLS": "https://+:443;http://+:80"
},
"publishAllPorts": true,
"useSSL": true
}
},
"$schema": "https://json.schemastore.org/launchsettings.json",
"iisSettings": {
"windowsAuthentication": false,
"anonymousAuthentication": true,
"iisExpress": {
"applicationUrl": "http://localhost:36974",
"sslPort": 44370
}
}
}

View File

@ -0,0 +1,8 @@
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
}
}

View File

@ -0,0 +1,9 @@
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*"
}

View File

@ -0,0 +1,30 @@
**/.classpath
**/.dockerignore
**/.env
**/.git
**/.gitignore
**/.project
**/.settings
**/.toolstarget
**/.vs
**/.vscode
**/*.*proj.user
**/*.dbmdl
**/*.jfm
**/azds.yaml
**/bin
**/charts
**/docker-compose*
**/Dockerfile*
**/node_modules
**/npm-debug.log
**/obj
**/secrets.dev.yaml
**/values.dev.yaml
LICENSE
README.md
!**/.gitignore
!.git/HEAD
!.git/config
!.git/packed-refs
!.git/refs/heads/**

View File

@ -0,0 +1,112 @@
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Hosting;
using RestSharp;
namespace WorkerService.Controllers
{
[ApiController]
[Route("[controller]")]
public class HomeController : ControllerBase
{
private readonly ILogger<HomeController> _logger;
private readonly RestClient _restClient;
public static List<WorkerEntity> list = new List<WorkerEntity>();
public HomeController(ILogger<HomeController> logger)
{
_logger = logger;
_restClient = new RestClient("http://nginx/postservice/Home");
}
[HttpGet("get")]
public IActionResult Get()
{
if (list == null || list.Count == 0)
{
return NotFound();
}
var result = list.Select(l => new GetEntity
{
Id = l.Id,
FIO = l.FIO,
PostId = l.PostId,
});
return Ok(result);
}
[HttpGet("get/{Id}")]
public IActionResult Get([FromRoute] Guid Id)
{
var obj = list.Where(l => l.Id == Id);
return obj == null ? NotFound() : Ok(obj);
}
[HttpPost("create")]
public async Task<IActionResult> CreateAsync([FromBody] CreateUpdateWorker data)
{
try
{
var model = new WorkerEntity()
{
Id = Guid.NewGuid(),
FIO = data.FIO,
PostId = data.PostId,
};
var restRequest = new RestRequest($"/get/{data.PostId}", Method.Get);
var responce = await _restClient.ExecuteAsync<PostEntity>(restRequest);
if (!responce.IsSuccessful)
{
return BadRequest(responce);
}
model.Post = responce.Data;
list.Add(model);
return Ok(model);
}
catch (Exception ex)
{
return BadRequest(ex.Message);
}
}
[HttpPut("update/{Id}")]
public IActionResult Update([FromRoute] Guid Id,
[FromBody] CreateUpdateWorker data)
{
var oldModel = list.Where(l => l.Id == Id).Select(l => list.IndexOf(l)).FirstOrDefault();
if (oldModel != null)
{
list[oldModel].FIO = data.FIO;
list[oldModel].PostId = data.PostId;
var modelForResult = new CreateUpdateWorker
{
FIO = data.FIO,
PostId = data.PostId,
};
return Ok(modelForResult);
}
else return NotFound();
}
[HttpDelete("delete/{Id}")]
public IActionResult Delete([FromRoute] Guid Id)
{
var model = list.Where(l => l.Id != Id).FirstOrDefault();
if (model != null)
{
list.Remove(model);
return Ok();
}
else return NotFound();
}
}
}

View File

@ -0,0 +1,24 @@
#See https://aka.ms/customizecontainer to learn how to customize your debug container and how Visual Studio uses this Dockerfile to build your images for faster debugging.
FROM mcr.microsoft.com/dotnet/aspnet:6.0 AS base
WORKDIR /app
EXPOSE 80
EXPOSE 443
FROM mcr.microsoft.com/dotnet/sdk:6.0 AS build
ARG BUILD_CONFIGURATION=Release
WORKDIR /src
COPY ["WorkerService.csproj", "."]
RUN dotnet restore "./WorkerService.csproj"
COPY . .
WORKDIR "/src/."
RUN dotnet build "./WorkerService.csproj" -c $BUILD_CONFIGURATION -o /app/build
FROM build AS publish
ARG BUILD_CONFIGURATION=Release
RUN dotnet publish "./WorkerService.csproj" -c $BUILD_CONFIGURATION -o /app/publish /p:UseAppHost=false
FROM base AS final
WORKDIR /app
COPY --from=publish /app/publish .
ENTRYPOINT ["dotnet", "WorkerService.dll"]

View File

@ -0,0 +1,32 @@
namespace WorkerService
{
public class WorkerEntity
{
public Guid Id { get; set; }
public string FIO { get; set; }
public Guid PostId { get; set; }
public PostEntity Post { get; set; }
}
public class PostEntity
{
public Guid id { get; set; }
public string name { get; set; }
}
public class CreateUpdateWorker
{
public string FIO { get; set; }
public Guid PostId { get; set; }
}
public class GetEntity
{
public Guid Id { get; set; }
public string FIO { get; set; }
public Guid PostId { get; set; }
}
}

View File

@ -0,0 +1,32 @@
using Microsoft.OpenApi.Models;
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
var app = builder.Build();
app.UseSwagger(c =>
{
c.PreSerializeFilters.Add((swaggerDoc, httpReq) =>
{
swaggerDoc.Servers = new List<OpenApiServer> { new OpenApiServer { Url = $"{httpReq.Scheme}://{httpReq.Host.Value}/workerservice" } };
});
});
app.UseSwaggerUI();
app.UseHttpsRedirection();
app.UseAuthorization();
app.MapControllers();
app.Run();

View File

@ -0,0 +1,41 @@
{
"profiles": {
"WorkerService": {
"commandName": "Project",
"launchBrowser": true,
"launchUrl": "swagger",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
},
"dotnetRunMessages": true,
"applicationUrl": "https://localhost:7144;http://localhost:5220"
},
"IIS Express": {
"commandName": "IISExpress",
"launchBrowser": true,
"launchUrl": "swagger",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
},
"Container (Dockerfile)": {
"commandName": "Docker",
"launchBrowser": true,
"launchUrl": "{Scheme}://{ServiceHost}:{ServicePort}/swagger",
"environmentVariables": {
"ASPNETCORE_URLS": "https://+:443;http://+:80"
},
"publishAllPorts": true,
"useSSL": true
}
},
"$schema": "https://json.schemastore.org/launchsettings.json",
"iisSettings": {
"windowsAuthentication": false,
"anonymousAuthentication": true,
"iisExpress": {
"applicationUrl": "http://localhost:55850",
"sslPort": 44303
}
}
}

View File

@ -0,0 +1,18 @@
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<TargetFramework>net6.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
<UserSecretsId>3228803c-add9-46fb-b949-9e2a2e89056a</UserSecretsId>
<DockerDefaultTargetOS>Linux</DockerDefaultTargetOS>
<DockerfileContext>.</DockerfileContext>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.VisualStudio.Azure.Containers.Tools.Targets" Version="1.20.1" />
<PackageReference Include="RestSharp" Version="112.0.0" />
<PackageReference Include="Swashbuckle.AspNetCore" Version="6.5.0" />
</ItemGroup>
</Project>

View File

@ -0,0 +1,9 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="Current" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<ActiveDebugProfile>WorkerService</ActiveDebugProfile>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|AnyCPU'">
<DebuggerFlavor>ProjectDebugger</DebuggerFlavor>
</PropertyGroup>
</Project>

View File

@ -0,0 +1,25 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 17
VisualStudioVersion = 17.10.35004.147
MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "WorkerService", "WorkerService.csproj", "{A9DF2332-E571-49AD-805A-D61B23C40D5F}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{A9DF2332-E571-49AD-805A-D61B23C40D5F}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{A9DF2332-E571-49AD-805A-D61B23C40D5F}.Debug|Any CPU.Build.0 = Debug|Any CPU
{A9DF2332-E571-49AD-805A-D61B23C40D5F}.Release|Any CPU.ActiveCfg = Release|Any CPU
{A9DF2332-E571-49AD-805A-D61B23C40D5F}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {B515427C-329A-4B73-B82C-45D929A6EA75}
EndGlobalSection
EndGlobal

View File

@ -0,0 +1,8 @@
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
}
}

View File

@ -0,0 +1,9 @@
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*"
}

View File

@ -0,0 +1,21 @@
services:
nginx:
image: nginx
depends_on:
- postservice
- workerservice
volumes:
- ./nginx/nginx.conf:/etc/nginx/conf.d/default.conf
ports:
- 80:80
postservice:
build: .\PostService
ports:
- 81:8080
workerservice:
build: .\WorkerService
ports:
- 82:8080
depends_on:
- postservice

View File

@ -0,0 +1,21 @@
server {
listen 80;
listen [::]:80;
server_name localhost;
location /postservice/ {
proxy_pass http://postservice:80/;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_set_header X-Forwarded-Prefix /admin;
}
location /workerservice/ {
proxy_pass http://workerservice:80/;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_set_header X-Forwarded-Prefix /admin;
}
}

View File

@ -0,0 +1,16 @@
# Лабораторная работа 3
В работе представлен пример синхронного обмена сообщениями между сервисами и их взаимодейсвием с внешним миром.
## Описание
Были взяты две сущности: работник и должность. Первый сервис позволяет манипулировать списком должностей, второй - списком работников, у каждого из которых может быть одна должность. У одной должности может быть много работников.
Реализована система была с помощью web-api на c# с хранением данных в оперативной памяти.
В качестве интерфейса используется Swagger, который можно использовать для отправки запросов.
## Запуск
Для запуска лабораторной работы необходимо иметь запущенный Docker.
Необходимо перейти в папку, где располагается данный файл. Далее открыть терминал и ввести команду:
```
docker compose up -d --build
```
Важно, чтобы в этот момент на компьютере был свободен порт 80.
В результате, после сборки вся система запустится и Swagger-ы будут доступны по путям http://localhost/postservice/swagger и http://localhost/workerservice/swagger
## Видеодемонстрация
Видеодемонстрация результата лабораторной работы представлена по [адресу](https://drive.google.com/file/d/1rg2xnXM-jPDfFJWxNIitq0I8kXj9Pr3-/view?usp=sharing)