Here's a C# implementation of an API endpoint that sorts characters in a word using ASP.NET Core. This example includes a controller, model, and necessary setup:
// 1. First, create a model for the request
public class SortWordRequest
{
public string Word { get; set; }
}
// 2. Create the controller
using Microsoft.AspNetCore.Mvc;
using System.Linq;
[Route("api/[controller]")]
[ApiController]
public class WordSortController : ControllerBase
{
[HttpPost("sort")]
public ActionResult<string> SortWord([FromBody] SortWordRequest request)
{
try
{
// Validate input
if (string.IsNullOrWhiteSpace(request?.Word))
{
return BadRequest("Word cannot be empty or null");
}
// Sort the characters and return
string sortedWord = SortCharacters(request.Word);
return Ok(sortedWord);
}
catch (Exception ex)
{
return StatusCode(500, $"An error occurred: {ex.Message}");
}
}
private string SortCharacters(string word)
{
// Convert string to char array, sort it, and convert back to string
return new string(word.ToCharArray().OrderBy(c => c).ToArray());
}
}
// 3. Program.cs (for .NET 6+ minimal API alternative)
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.DependencyInjection;
var builder = WebApplication.CreateBuilder(args);
// Add services to the container
builder.Services.AddControllers();
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
var app = builder.Build();
// Configure the HTTP request pipeline
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}
app.UseHttpsRedirection();
app.UseAuthorization();
app.MapControllers();
app.Run();
// 4. Optional: Add error handling middleware
public class ErrorHandlingMiddleware
{
private readonly RequestDelegate _next;
public ErrorHandlingMiddleware(RequestDelegate next)
{
_next = next;
}
public async Task Invoke(HttpContext context)
{
try
{
await _next(context);
}
catch (Exception ex)
{
await HandleExceptionAsync(context, ex);
}
}
private static Task HandleExceptionAsync(HttpContext context, Exception exception)
{
context.Response.ContentType = "application/json";
context.Response.StatusCode = StatusCodes.Status500InternalServerError;
var result = System.Text.Json.JsonSerializer.Serialize(new
{
error = "An unexpected error occurred",
detail = exception.Message
});
return context.Response.WriteAsync(result);
}
}
To use this API:
-
Setup the Project:
-
API Endpoint:
- The endpoint will be available at:
POST /api/wordsort/sort
-
Sample Request:
{
"word": "hello"
}
-
Sample Response:
"ehllo"
-
Testing with cURL:
curl -X POST "https://localhost:5001/api/wordsort/sort" \
-H "Content-Type: application/json" \
-d '{"word":"hello"}'
Features of this Implementation:
-
Input Validation:
- Checks for null or empty input
- Returns appropriate HTTP status codes
-
Error Handling:
- Includes try-catch blocks
- Returns meaningful error messages
- Includes optional global error handling middleware
-
Swagger Support:
- Includes Swagger/OpenAPI documentation (when in development mode)
-
Flexibility:
- The sorting logic is separated into a private method for easy modification
- Can be extended to include additional sorting options (e.g., case-sensitive sorting)
Optional Enhancements:
- Case-Sensitive Sorting:
private string SortCharacters(string word, bool caseSensitive = false)
{
if (caseSensitive)
{
return new string(word.ToCharArray().OrderBy(c => c).ToArray());
}
return new string(word.ToLower().ToCharArray().OrderBy(c => c).ToArray());
}
- Add Validation Attributes:
public class SortWordRequest
{
[Required]
[StringLength(100, MinimumLength = 1)]
public string Word { get; set; }
}
- Add Response Model:
public class SortWordResponse
{
public string OriginalWord { get; set; }
public string SortedWord { get; set; }
}
- Add Unit Tests:
public class WordSortTests
{
[Fact]
public void SortCharacters_SortsWordCorrectly()
{
var controller = new WordSortController();
var result = controller.SortCharacters("hello");
Assert.Equal("ehllo", result);
}
}
To run the API:
- Set up the project in Visual Studio or use the .NET CLI
- Run the application
- Use Swagger UI (available at
/swagger in development mode) or any API testing tool to test the endpoint
Remember to:
- Add appropriate security measures for production use
- Consider rate limiting for public APIs
- Add logging for better monitoring
- Implement proper CORS policies if needed