Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Дунин Даниил, Кучин Степан, Ратушный Илья, Султанов Вячеслав #42

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion Tests/Task5_DeleteUserTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,7 @@ public async Task Test4_Code404_WhenAlreadyCreatedAndDeleted()
lastName = "Condenado"
});

DeleteUser(createdUserId);
await DeleteUser(createdUserId);

var request = new HttpRequestMessage();
request.Method = HttpMethod.Delete;
Expand Down
4 changes: 2 additions & 2 deletions Tests/UsersApiTestsBase.cs
Original file line number Diff line number Diff line change
Expand Up @@ -96,13 +96,13 @@ protected async Task<string> CreateUser(object user)
return createdUserId;
}

protected void DeleteUser(string userId)
protected async Task DeleteUser(string userId)
{
var request = new HttpRequestMessage();
request.Method = HttpMethod.Delete;
request.RequestUri = BuildUsersByIdUri(userId);
request.Headers.Add("Accept", "*/*");
var response = HttpClient.Send(request);
var response = await HttpClient.SendAsync(request).ConfigureAwait(false);

response.StatusCode.Should().Be(HttpStatusCode.NoContent);
response.ShouldNotHaveHeader("Content-Type");
Expand Down
167 changes: 161 additions & 6 deletions WebApi.MinimalApi/Controllers/UsersController.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,7 @@
using Microsoft.AspNetCore.Mvc;
using AutoMapper;
using Microsoft.AspNetCore.JsonPatch;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using WebApi.MinimalApi.Domain;
using WebApi.MinimalApi.Models;

Expand All @@ -9,19 +12,171 @@ namespace WebApi.MinimalApi.Controllers;
public class UsersController : Controller
{
// Чтобы ASP.NET положил что-то в userRepository требуется конфигурация
public UsersController(IUserRepository userRepository)
readonly private IUserRepository userRepository;
readonly private IMapper iMapper;
readonly private LinkGenerator linkGenerator;
public UsersController(IUserRepository userRepository, IMapper iMapper, LinkGenerator linkGenerator)
{
this.userRepository = userRepository;
this.iMapper = iMapper;
this.linkGenerator = linkGenerator;
}

[HttpGet("{userId}")]
[HttpHead("{userId}")]
[HttpGet("{userId}", Name = nameof(GetUserById))]
[Produces("application/json", "application/xml")]
public ActionResult<UserDto> GetUserById([FromRoute] Guid userId)
{
throw new NotImplementedException();
var user = userRepository.FindById(userId);
if (user == null)
{
return NotFound();
}

if (Request.HttpContext.Request.Method != "HEAD")
{
return Ok(iMapper.Map<UserDto>(user));
}

Response.ContentLength = 0;
Response.ContentType = "application/json; charset=utf-8";
return Ok();
}

[HttpPost]
public IActionResult CreateUser([FromBody] object user)
[Produces("application/json", "application/xml")]
public IActionResult CreateUser([FromBody] PostUserDto? user)
{
if (user is null)
{
return BadRequest();
}

if (!ModelState.IsValid)
{
return UnprocessableEntity(ModelState);
}

if (user.Login.Any(x => !char.IsLetterOrDigit(x)))
{
ModelState.AddModelError("login", "Should contain letters and numbers only");
return UnprocessableEntity(ModelState);
}

var createdUserEntity = userRepository.Insert(iMapper.Map<UserEntity>(user));
return CreatedAtRoute(
nameof(GetUserById),
new { userId = createdUserEntity.Id },
createdUserEntity.Id);
}

[HttpPut("{userId}")]
[Produces("application/json", "application/xml")]
public IActionResult UpdateUser([FromRoute] Guid userId, [FromBody] UpdateUserDto? user)
{
if (user is null)
{
return BadRequest();
}

if (userId == Guid.Empty)
{
return BadRequest();
}

if (!ModelState.IsValid)
{
return UnprocessableEntity(ModelState);
}

userRepository.UpdateOrInsert(iMapper.Map(user, new UserEntity(userId)), out var updatedUserEntity);
if (updatedUserEntity)
{
return CreatedAtRoute(
nameof(GetUserById),
new { userId },
userId);
}

return NoContent();
}

[HttpPatch("{userId}")]
[Produces("application/json", "application/xml")]
public IActionResult PartiallyUpdateUser([FromRoute] Guid userId, [FromBody] JsonPatchDocument<UpdateUserDto>? patchDoc)
{
if (patchDoc is null)
{
return BadRequest();
}

var user = new UpdateUserDto();
patchDoc.ApplyTo(user, ModelState);
if (userId == Guid.Empty)
{
return NotFound();
}

if (!TryValidateModel(user))
{
return UnprocessableEntity(ModelState);
}

var currentUser = userRepository.FindById(userId);
if (currentUser is null)
{
return NotFound();
}

userRepository.Update(iMapper.Map(user, new UserEntity(userId)));
return NoContent();
}

[HttpDelete("{userId}")]
[Produces("application/json", "application/xml")]
public IActionResult DeleteUser([FromRoute] Guid userId)
{
var currUser = userRepository.FindById(userId);
if (currUser is null)
{
return NotFound();
}

userRepository.Delete(userId);
return NoContent();
}

[HttpGet(Name = nameof(GetAllUsers))]
[Produces("application/json", "application/xml")]
public IActionResult GetAllUsers([FromQuery] int pageNumber = 1, [FromQuery] int pageSize = 10)
{
var realPageSize = pageSize > 20 ? 20 : pageSize;
var page = userRepository.GetPage(pageNumber, realPageSize);

var paginationHeader = new
{
currentPage = page.CurrentPage == 0 ? 1 : page.CurrentPage,
totalPages = page.TotalPages,
pageSize = page.PageSize == 0 ? 1 : page.PageSize,
totalCount = page.TotalCount,
nextPageLink = page.HasNext
? linkGenerator.GetUriByRouteValues(HttpContext, nameof(GetAllUsers), new { pageNumber = pageNumber + 1, pageSize } )
: null,
previousPageLink = page.HasPrevious
? linkGenerator.GetUriByRouteValues(HttpContext, nameof(GetAllUsers), new { pageNumber = pageNumber - 1, pageSize } )
: null,
};

Response.Headers.Append("X-Pagination", JsonConvert.SerializeObject(paginationHeader));
return Ok(iMapper.Map<IEnumerable<UserDto>>(page));
}

[HttpOptions]
[Produces("application/json", "application/xml")]
public IActionResult Options()
{
throw new NotImplementedException();
Response.Headers.Append("Allow", new[] { "GET", "POST", "OPTIONS" });
Response.ContentLength = 0;
return Ok();
}
}
16 changes: 16 additions & 0 deletions WebApi.MinimalApi/Models/PostUserDto.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;

namespace WebApi.MinimalApi.Models;

public class PostUserDto
{
[Required]
public string Login { get; set; }

[DefaultValue("John")]
public string FirstName { get; set; }

[DefaultValue("Doe")]
public string LastName { get; set; }
}
16 changes: 16 additions & 0 deletions WebApi.MinimalApi/Models/UpdateUserDto.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
using System.ComponentModel.DataAnnotations;

namespace WebApi.MinimalApi.Models;

public class UpdateUserDto
{
[Required]
[RegularExpression("^[0-9\\p{L}]*$", ErrorMessage = "Login should contain only letters or digits")]
public string Login { get; set; }

[Required]
public string FirstName { get; set; }

[Required]
public string LastName { get; set; }
}
33 changes: 31 additions & 2 deletions WebApi.MinimalApi/Program.cs
Original file line number Diff line number Diff line change
@@ -1,11 +1,40 @@
using Microsoft.AspNetCore.Mvc.Formatters;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
using WebApi.MinimalApi.Domain;
using WebApi.MinimalApi.Models;

var builder = WebApplication.CreateBuilder(args);
builder.WebHost.UseUrls("http://localhost:5000");
builder.Services.AddControllers()
builder.Services.AddControllers(options =>
{
// Этот OutputFormatter позволяет возвращать данные в XML, если требуется.
options.OutputFormatters.Add(new XmlDataContractSerializerOutputFormatter());
// Эта настройка позволяет отвечать кодом 406 Not Acceptable на запросы неизвестных форматов.
options.ReturnHttpNotAcceptable = true;
// Эта настройка приводит к игнорированию заголовка Accept, когда он содержит */*
// Здесь она нужна, чтобы в этом случае ответ возвращался в формате JSON
options.RespectBrowserAcceptHeader = true;
})
.ConfigureApiBehaviorOptions(options => {
options.SuppressModelStateInvalidFilter = true;
options.SuppressMapClientErrors = true;
})
.AddNewtonsoftJson(options =>
{
options.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
options.SerializerSettings.DefaultValueHandling = DefaultValueHandling.Populate;
});

builder.Services.AddAutoMapper(cfg =>
{
cfg.CreateMap<UserEntity, UserDto>()
.ForMember(dto => dto.FullName,
opt => opt.MapFrom(user => $"{user.LastName} {user.FirstName}"));
cfg.CreateMap<PostUserDto, UserEntity>();
cfg.CreateMap<UpdateUserDto, UserEntity>();
cfg.CreateMap<IEnumerable<UserDto>, PageList<UserEntity>>();
}, new System.Reflection.Assembly[0]);
builder.Services.AddSingleton<IUserRepository, InMemoryUserRepository>();
var app = builder.Build();

app.MapControllers();
Expand Down
5 changes: 5 additions & 0 deletions web-api.sln.DotSettings
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,10 @@
<s:String x:Key="/Default/CodeStyle/Naming/CSharpNaming/PredefinedNamingRules/=PrivateStaticFields/@EntryIndexedValue">&lt;Policy Inspect="True" Prefix="" Suffix="" Style="aaBb" /&gt;</s:String>
<s:String x:Key="/Default/CodeStyle/Naming/CSharpNaming/PredefinedNamingRules/=PrivateStaticReadonly/@EntryIndexedValue">&lt;Policy Inspect="True" Prefix="" Suffix="" Style="AaBb"&gt;&lt;ExtraRule Prefix="" Suffix="" Style="aaBb" /&gt;&lt;/Policy&gt;</s:String>
<s:String x:Key="/Default/CodeStyle/Naming/CSharpNaming/PredefinedNamingRules/=TypesAndNamespaces/@EntryIndexedValue">&lt;Policy Inspect="True" Prefix="" Suffix="" Style="AaBb_AaBb" /&gt;</s:String>
<s:String x:Key="/Default/CodeStyle/Naming/CSharpNaming/UserRules/=15b5b1f1_002D457c_002D4ca6_002Db278_002D5615aedc07d3/@EntryIndexedValue">&lt;Policy&gt;&lt;Descriptor Staticness="Static" AccessRightKinds="Private" Description="Static readonly fields (private)"&gt;&lt;ElementKinds&gt;&lt;Kind Name="READONLY_FIELD" /&gt;&lt;/ElementKinds&gt;&lt;/Descriptor&gt;&lt;Policy Inspect="True" Prefix="" Suffix="" Style="AaBb"&gt;&lt;ExtraRule Prefix="" Suffix="" Style="aaBb" /&gt;&lt;/Policy&gt;&lt;/Policy&gt;</s:String>
<s:String x:Key="/Default/CodeStyle/Naming/CSharpNaming/UserRules/=4a98fdf6_002D7d98_002D4f5a_002Dafeb_002Dea44ad98c70c/@EntryIndexedValue">&lt;Policy&gt;&lt;Descriptor Staticness="Instance" AccessRightKinds="Private" Description="Instance fields (private)"&gt;&lt;ElementKinds&gt;&lt;Kind Name="FIELD" /&gt;&lt;Kind Name="READONLY_FIELD" /&gt;&lt;/ElementKinds&gt;&lt;/Descriptor&gt;&lt;Policy Inspect="True" Prefix="" Suffix="" Style="aaBb" /&gt;&lt;/Policy&gt;</s:String>
<s:String x:Key="/Default/CodeStyle/Naming/CSharpNaming/UserRules/=a0b4bc4d_002Dd13b_002D4a37_002Db37e_002Dc9c6864e4302/@EntryIndexedValue">&lt;Policy&gt;&lt;Descriptor Staticness="Any" AccessRightKinds="Any" Description="Types and namespaces"&gt;&lt;ElementKinds&gt;&lt;Kind Name="NAMESPACE" /&gt;&lt;Kind Name="CLASS" /&gt;&lt;Kind Name="STRUCT" /&gt;&lt;Kind Name="ENUM" /&gt;&lt;Kind Name="DELEGATE" /&gt;&lt;/ElementKinds&gt;&lt;/Descriptor&gt;&lt;Policy Inspect="True" Prefix="" Suffix="" Style="AaBb_AaBb" /&gt;&lt;/Policy&gt;</s:String>
<s:String x:Key="/Default/CodeStyle/Naming/CSharpNaming/UserRules/=f9fce829_002De6f4_002D4cb2_002D80f1_002D5497c44f51df/@EntryIndexedValue">&lt;Policy&gt;&lt;Descriptor Staticness="Static" AccessRightKinds="Private" Description="Static fields (private)"&gt;&lt;ElementKinds&gt;&lt;Kind Name="FIELD" /&gt;&lt;/ElementKinds&gt;&lt;/Descriptor&gt;&lt;Policy Inspect="True" Prefix="" Suffix="" Style="aaBb" /&gt;&lt;/Policy&gt;</s:String>
<s:String x:Key="/Default/CodeStyle/Naming/JavaScriptNaming/UserRules/=JS_005FBLOCK_005FSCOPE_005FCONSTANT/@EntryIndexedValue">&lt;Policy Inspect="True" Prefix="" Suffix="" Style="aaBb" /&gt;</s:String>
<s:String x:Key="/Default/CodeStyle/Naming/JavaScriptNaming/UserRules/=JS_005FBLOCK_005FSCOPE_005FFUNCTION/@EntryIndexedValue">&lt;Policy Inspect="True" Prefix="" Suffix="" Style="aaBb" /&gt;</s:String>
<s:String x:Key="/Default/CodeStyle/Naming/JavaScriptNaming/UserRules/=JS_005FBLOCK_005FSCOPE_005FVARIABLE/@EntryIndexedValue">&lt;Policy Inspect="True" Prefix="" Suffix="" Style="aaBb" /&gt;</s:String>
Expand Down Expand Up @@ -69,4 +73,5 @@
<s:Boolean x:Key="/Default/Environment/SettingsMigration/IsMigratorApplied/=JetBrains_002EReSharper_002EPsi_002ECSharp_002ECodeStyle_002ESettingsUpgrade_002ECSharpPlaceAttributeOnSameLineMigration/@EntryIndexedValue">True</s:Boolean>
<s:Boolean x:Key="/Default/Environment/SettingsMigration/IsMigratorApplied/=JetBrains_002EReSharper_002EPsi_002ECSharp_002ECodeStyle_002ESettingsUpgrade_002EMigrateBlankLinesAroundFieldToBlankLinesAroundProperty/@EntryIndexedValue">True</s:Boolean>
<s:Boolean x:Key="/Default/Environment/SettingsMigration/IsMigratorApplied/=JetBrains_002EReSharper_002EPsi_002ECSharp_002ECodeStyle_002ESettingsUpgrade_002EMigrateThisQualifierSettings/@EntryIndexedValue">True</s:Boolean>
<s:Boolean x:Key="/Default/Environment/SettingsMigration/IsMigratorApplied/=JetBrains_002EReSharper_002EPsi_002ECSharp_002ECodeStyle_002ESettingsUpgrade_002EPredefinedNamingRulesToUserRulesUpgrade/@EntryIndexedValue">True</s:Boolean>
<s:Boolean x:Key="/Default/Environment/SettingsMigration/IsMigratorApplied/=JetBrains_002EReSharper_002EPsi_002EFormat_002ESettingsUpgrade_002EAlignmentTabFillStyleMigration/@EntryIndexedValue">True</s:Boolean></wpf:ResourceDictionary>