gpt-4-0314· openai
Suzhen/CodeChat
напиши код webapi на asp.net core простенького сайта для знакомств
- User
напиши код webapi на asp.net core простенького сайта для знакомств
- Assistant
напиши код webapi на asp.net core простенького сайта для знакомств
В этом примере мы создадим простой ASP.NET Core Web API для сайта знакомств с основными операциями CRUD (создание, чтение, обновление и удаление).
dotnet new webapi --name DatingApp
cd DatingApp
UserProfile:// Models/UserProfile.cs
using System.ComponentModel.DataAnnotations;
namespace DatingApp.Models
{
public class UserProfile
{
[Required]
public int Id { get; set; }
[Required]
[StringLength(100)]
public string Name { get; set; }
[Required]
[Range(18, 99)]
public int Age { get; set; }
[Required]
[StringLength(100)]
public string Location { get; set; }
[StringLength(500)]
public string Bio { get; set; }
}
}
IUserRepository:// IData/IUserRepository.cs
using System.Collections.Generic;
using DatingApp.Models;
namespace DatingApp.IData
{
public interface IUserRepository
{
IEnumerable<UserProfile> GetAllProfiles();
UserProfile GetProfileById(int id);
UserProfile CreateProfile(UserProfile profile);
UserProfile UpdateProfile(int id, UserProfile profile);
void DeleteProfile(int id);
}
}
UserRepository:// Data/UserRepository.cs
using System.Collections.Generic;
using System.Linq;
using DatingApp.IData;
using DatingApp.Models;
namespace DatingApp.Data
{
public class UserRepository : IUserRepository
{
private readonly List<UserProfile> _profiles = new List<UserProfile>();
public IEnumerable<UserProfile> GetAllProfiles() => _profiles;
public UserProfile GetProfileById(int id) => _profiles.FirstOrDefault(p => p.Id == id);
public UserProfile CreateProfile(UserProfile profile)
{
profile.Id = _profiles.Count + 1;
_profiles.Add(profile);
return profile;
}
public UserProfile UpdateProfile(int id, UserProfile profile)
{
var toBeUpdated = _profiles.FirstOrDefault(p => p.Id == id);
if (toBeUpdated != null)
{
_profiles.Remove(toBeUpdated);
profile.Id = id;
_profiles.Add(profile);
return profile;
}
return null;
}
public void DeleteProfile(int id)
{
var toBeDeleted = _profiles.FirstOrDefault(p => p.Id == id);
if (toBeDeleted != null)
{
_profiles.Remove(toBeDeleted);
}
}
}
}
UserRepository в IoC-контейнере:// Startup.cs
using DatingApp.Data;
using DatingApp.IData;
// ...
public void ConfigureServices(IServiceCollection services)
{
services.AddScoped<IUserRepository, UserRepository>();
services.AddControllers();
}
UsersController:// Controllers/UsersController.cs
using System;
using System.Collections.Generic;
using DatingApp.Models;
using Microsoft.AspNetCore.Mvc;
using DatingApp.IData;
namespace DatingApp.Controllers
{
[ApiController]
[Route("[controller]")]
public class UsersController : ControllerBase
{
private readonly IUserRepository _repository;
public UsersController(IUserRepository repository)
{
_repository = repository;
}
[HttpGet]
public IEnumerable<UserProfile> GetAllProfiles() => _repository.GetAllProfiles();
[HttpGet("{id}")]
public ActionResult<UserProfile> GetProfileById(int id)
{
var profile = _repository.GetProfileById(id);
if (profile == null)
{
return NotFound();
}
return profile;
}
[HttpPost]
public ActionResult<UserProfile> CreateProfile([FromBody] UserProfile profile)
{
return _repository.CreateProfile(profile);
}
[HttpPut("{id}")]
public ActionResult<UserProfile> UpdateProfile(int id, [FromBody] UserProfile profile)
{
var updatedProfile = _repository.UpdateProfile(id, profile);
if (updatedProfile == null)
{
return NotFound();
}
return updatedProfile;
}
[HttpDelete("{id}")]
public IActionResult DeleteProfile(int id)
{
_repository.DeleteProfile(id);
return NoContent();
}
}
}
Теперь у вас есть примитивный ASP.NET Core Web API для сайта знакомств с операциями CRUD для работы с профилями пользователей. Вы можете запустить его и использовать клиентскую программу (например, Postman) для тестирования.