CSharp Web API Concepts: Difference between revisions
Jump to navigation
Jump to search
Line 44: | Line 44: | ||
</syntaxhighlight> | </syntaxhighlight> | ||
=Validation of Request= | =Validation of Request= | ||
So I implement this with middleware in typescript too but watching youtube has led me to. | So I implement this with middleware in typescript too but watching youtube has led me to two approaches | ||
*Fluent Validation (3rd party) | |||
*Data Validation (Microsoft | |||
==Fluent Validation== | |||
Lets install it first | |||
<syntaxhighlight lang="bash"> | |||
dotnet add package FluentValidation.DependencyInjectionExtensions | |||
</syntaxhighlight> | |||
Add the service | |||
<syntaxhighlight lang="cs"> | <syntaxhighlight lang="cs"> | ||
... | |||
builder.Services.AddValidatorsFromAssemblyContaining<Program>(); | |||
... | |||
</syntaxhighlight> | </syntaxhighlight> | ||
I am going to valid a request for a vehicle which can have a rego or a responsibility code. |
Revision as of 04:33, 22 November 2024
Introduction
This pages is to capture some useful thing around the Web API.
Middleware
I was trying to match up my Typescript work with C# so I started off be looking a middleware. Not a difficult concept. So for .NET 8.0 for me it consisting of
- Making and Extension
- Applying the extension
- Implementing the middleware
Pretty straight forward
// Create an extension
public static IApplicationBuilder UseCustomMiddleware(this IApplicationBuilder app)
{
return app.UseMiddleware<CustomMiddleware>();
}
// Applying the extension
...
var app = builder.Build();
app.UseCustomMiddleware();
app.MapGet("/", (HttpContext context) =>
{
return "Hello World!";
});
...
// Implementing the middleware
public class CustomMiddleware
{
private readonly RequestDelegate _next;
public CustomMiddleware(RequestDelegate next)
{
_next = next;
}
public async Task Invoke(HttpContext context)
{
Console.WriteLine($"Request: {context.Request.Path}");
await _next(context);
}
}
Validation of Request
So I implement this with middleware in typescript too but watching youtube has led me to two approaches
- Fluent Validation (3rd party)
- Data Validation (Microsoft
Fluent Validation
Lets install it first
dotnet add package FluentValidation.DependencyInjectionExtensions
Add the service
...
builder.Services.AddValidatorsFromAssemblyContaining<Program>();
...
I am going to valid a request for a vehicle which can have a rego or a responsibility code.