Setup RestAPI, added role controller

This commit is contained in:
mfnefd 2024-06-05 01:25:18 +04:00
parent 57f90eaa82
commit 681118ff91
7 changed files with 179 additions and 52 deletions

View File

@ -0,0 +1,120 @@
using BusinessLogic.BusinessLogic;
using Contracts.BindingModels;
using Contracts.BusinessLogicContracts;
using Contracts.Exceptions;
using Contracts.SearchModels;
using Contracts.ViewModels;
using Microsoft.AspNetCore.Http.HttpResults;
using Microsoft.AspNetCore.Mvc;
namespace RestAPI.Controllers
{
[Route("[controller]/[action]")]
[ApiController]
public class RoleController
{
private readonly ILogger _logger;
private readonly IRoleLogic _roleLogic;
public RoleController(ILogger<RoleController> logger, IRoleLogic roleLogic)
{
_logger = logger;
_roleLogic = roleLogic;
}
[HttpGet]
public IResult Get([FromQuery] RoleSearchModel model)
{
try
{
var res = _roleLogic.ReadElement(model);
return Results.Ok(res);
}
catch (ElementNotFoundException ex)
{
_logger.LogInformation(ex, "Element not found");
return Results.NoContent();
}
catch (Exception ex)
{
_logger.LogError(ex, "Error get role");
return Results.Problem(ex.Message);
}
}
[HttpGet]
public IResult GeFilteredtList([FromQuery] RoleSearchModel model)
{
try
{
var res = _roleLogic.ReadElements(model).ToList();
return Results.Ok(res);
}
catch (Exception ex)
{
_logger.LogError(ex, "Error get list role");
return Results.Problem(ex.Message);
}
}
[HttpGet]
public IResult GetList()
{
try
{
var res = _roleLogic.ReadElements(null).ToList();
return Results.Ok(res);
}
catch (Exception ex)
{
_logger.LogError(ex, "Error get list role");
return Results.Problem(ex.Message);
}
}
[HttpPost]
public IResult Create([FromBody] RoleBindingModel model)
{
try
{
var res = _roleLogic.Create(model);
return Results.Created(string.Empty, res);
}
catch (Exception ex)
{
_logger.LogError(ex, "Error create role");
return Results.Problem(ex.Message);
}
}
[HttpPut]
public IResult Update([FromBody] RoleBindingModel model)
{
try
{
var res = _roleLogic.Update(model);
return Results.Ok(res);
}
catch (Exception ex)
{
_logger.LogError(ex, "Error update role");
return Results.Problem(ex.Message);
}
}
[HttpDelete]
public IResult Delete([FromQuery] RoleSearchModel model)
{
try
{
var res = _roleLogic.Delete(model); ;
return Results.Ok(res);
}
catch (Exception ex)
{
_logger.LogError(ex, "Error delete role");
return Results.Problem(ex.Message);
}
}
}
}

View File

@ -1,33 +0,0 @@
using Microsoft.AspNetCore.Mvc;
namespace RestAPI.Controllers
{
[ApiController]
[Route("[controller]")]
public class WeatherForecastController : ControllerBase
{
private static readonly string[] Summaries = new[]
{
"Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
};
private readonly ILogger<WeatherForecastController> _logger;
public WeatherForecastController(ILogger<WeatherForecastController> logger)
{
_logger = logger;
}
[HttpGet(Name = "GetWeatherForecast")]
public IEnumerable<WeatherForecast> Get()
{
return Enumerable.Range(1, 5).Select(index => new WeatherForecast
{
Date = DateOnly.FromDateTime(DateTime.Now.AddDays(index)),
TemperatureC = Random.Shared.Next(-20, 55),
Summary = Summaries[Random.Shared.Next(Summaries.Length)]
})
.ToArray();
}
}
}

View File

@ -1,19 +1,43 @@
using BusinessLogic.BusinessLogic;
using Contracts.BusinessLogicContracts;
using Contracts.StorageContracts;
using DatabaseImplement.Implements;
using Microsoft.OpenApi.Models;
using System;
const string VERSION = "v1";
const string TITLE = "21GunsRestAPI";
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Logging.SetMinimumLevel(LogLevel.Trace);
builder.Logging.AddLog4Net("log4net.config");
#region DI
builder.Services.AddTransient<IRoleLogic, RoleLogic>();
builder.Services.AddTransient<IUserLogic, UserLogic>();
builder.Services.AddTransient<IRoleStorage, RoleStorage>();
builder.Services.AddTransient<IUserStorage, UserStorage>();
#endregion DI
builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
builder.Services.AddSwaggerGen(c =>
{
c.SwaggerDoc(VERSION, new OpenApiInfo { Title = TITLE, Version = VERSION });
});
var app = builder.Build();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
app.UseSwagger();
app.UseSwaggerUI(c => c.SwaggerEndpoint($"/swagger/{VERSION}/swagger.json", $"{TITLE} {VERSION}"));
}
app.UseHttpsRedirection();
@ -22,4 +46,4 @@ app.UseAuthorization();
app.MapControllers();
app.Run();
app.Run();

View File

@ -11,7 +11,20 @@
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="Microsoft.Extensions.Logging.Log4Net.AspNetCore" Version="8.0.0" />
<PackageReference Include="Swashbuckle.AspNetCore" Version="6.4.0" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\BusinessLogic\BusinessLogic.csproj" />
<ProjectReference Include="..\Contracts\Contracts.csproj" />
<ProjectReference Include="..\DatabaseImplement\DatabaseImplement.csproj" />
</ItemGroup>
<ItemGroup>
<Content Update="log4net.config">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</Content>
</ItemGroup>
</Project>

View File

@ -1,6 +1,6 @@
@RestAPI_HostAddress = http://localhost:5168
GET {{RestAPI_HostAddress}}/weatherforecast/
GET {{RestAPI_HostAddress}}/api/
Accept: application/json
###

View File

@ -1,13 +0,0 @@
namespace RestAPI
{
public class WeatherForecast
{
public DateOnly Date { get; set; }
public int TemperatureC { get; set; }
public int TemperatureF => 32 + (int)(TemperatureC / 0.5556);
public string? Summary { get; set; }
}
}

16
RestAPI/log4net.config Normal file
View File

@ -0,0 +1,16 @@
<?xml version="1.0" encoding="utf-8" ?>
<log4net>
<appender name="RollingFile" type="log4net.Appender.RollingFileAppender">
<file value="c:/temp/RestAPI.log" />
<appendToFile value="true" />
<maximumFileSize value="100KB" />
<maxSizeRollBackups value="2" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date %5level %logger.%method [%line] - MESSAGE: %message%newline %exception" />
</layout>
</appender>
<root>
<level value="TRACE" />
<appender-ref ref="RollingFile" />
</root>
</log4net>