September 2 2024
Explore it here.
[ApiController]
[Route("api/[controller]")]
public class UsersController : ControllerBase
{
private readonly IUserService _userService;
public UsersController(IUserService userService)
{
_userService = userService;
}
// POST api/users
[HttpPost]
public async Task<ActionResult<UserDto>> CreateUser([FromBody] CreateUserDto createUserDto)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
var createdUser = await _userService.CreateUserAsync(createUserDto);
return CreatedAtAction(nameof(GetUserById), new { id = createdUser.Id }, createdUser);
}
}
public class CreateUserRequest
{
public string Username { get; set; };
public string Email { get; set; };
public string Password { get; set; };
}
[Produces(MediaTypeNames.Application.Json)]
[Consumes(MediaTypeNames.Application.Json)]
[Route("api/[controller]")]
[ApiController]
public class CreateUserController : ControllerBase
{
[HttpPost(Name = "CreateUser")]
[ProducesResponseType(StatusCodes.Status204NoContent)]
public async Task<IActionResult> CreateCustomerAsync(CreateUserRequest createUserRequest)
{
var result = await _userService.CreateUserAsync(request);
return result.Success ? Ok(result.Data) : BadRequest(result.ErrorMessage);
}
}
public class ApiResponse<T>
{
public bool Success { get; set; };
public T Data { get; set; };
public string ErrorMessage { get; set; };
public static ApiResponse<T> SuccessResponse(T data) => new ApiResponse<T> { Success = true, Data = data };
public static ApiResponse<T> ErrorResponse(string errorMessage) => new ApiResponse<T> { Success = false, ErrorMessage = errorMessage };
}
[Produces(MediaTypeNames.Application.Json)]
[Consumes(MediaTypeNames.Application.Json)]
[Route("api/[controller]")]
[ApiController]
public class CreateUserController : ControllerBase
{
[HttpPost(Name = "CreateUser")]
[ProducesResponseType(StatusCodes.Status204NoContent)]
public async Task<IActionResult> CreateCustomerAsync(CreateUserRequest createUserRequest)
{
var result = await _userService.CreateUserAsync(request);
if (result.Success)
{
return Ok(ApiResponse<User>.SuccessResponse(result.Data));
}
else
{
return BadRequest(ApiResponse<string>.ErrorResponse(result.ErrorMessage));
}
}
}
using FastEndpoints;
public class CreateUserEndpoint : Endpoint<CreateUserRequest, CreateUserResponse>
{
public override void Configure()
{
Post("/api/users/create");
AllowAnonymous();
}
public override async Task HandleAsync(CreateUserRequest req, CancellationToken ct)
{
// Example: Validate input data
if (string.IsNullOrEmpty(req.Username) || string.IsNullOrEmpty(req.Email) || string.IsNullOrEmpty(req.Password))
{
await SendAsync(new CreateUserResponse
{
Success = false,
Message = "Invalid input data. Please provide all required fields."
});
return;
}
// Example: Simulate user creation logic (e.g., save to database and hash password)
// Here, we're simulating a successful user creation with a hardcoded user ID
int newUserId = 123; // Replace this with actual logic to save the user and retrieve the ID
// Example: Assume user creation was successful
await SendAsync(new CreateUserResponse
{
Success = true,
Message = "User created successfully.",
UserId = newUserId
});
}
}
Every Endpoint, and consequently each Controller, will be displayed individually in the Swagger documentation. Thankfully, there's a way to manage this. By utilizing Tags in the SwaggerOperation attribute, we can organize them into groups. Below is a code snippet demonstrating how to do this:
[SwaggerOperation(
Tags = new[] { "UserEndpoints" }
)]
Join 13,250+ subscribers to improve your .NET Knowledge.
Go-to resource for understanding the core concepts of design patterns without the overwhelming complexity. In this concise and affordable ebook, I've distilled the essence of design patterns into an easy-to-digest format. It is a Beginner level. Check out it here.
Every Monday morning, I share 1 actionable tip on C#, .NET & Arcitecture topic, that you can use right away.
Subscribe to the TheCodeMan.net and be among the 13,250+ subscribers gaining practical tips and resources to enhance your .NET expertise.