Giter Site home page Giter Site logo

bloodshop / superheroapi-postman Goto Github PK

View Code? Open in Web Editor NEW
0.0 1.0 0.0 35 KB

ASP.NET Web api & Entity Framework (CRUD, Repository Pattenm, DI, SQL Server, Swagger, Authorization and more) while create token and validation to access certain api calls

C# 100.00%
api asp-net-core cors endpoints jwt mvc postman sql swagger carter

superheroapi-postman's Introduction

SuperHeroApi - Minimal api using carter

Short video of using postman request api with token authorization

https://www.screencast.com/t/E3igDLQE , https://stackoverflow.com/a/74616217/19827098

CarterModule implementation and passing the endpoint to the base

public class SuperHeroesEndpoints : CarterModule
{
    public SuperHeroesEndpoints() : base("/superheroes") { }

    public override void AddRoutes(IEndpointRouteBuilder app)
    {
        app.MapGet("/list", List).Produces<List<SuperHero>>(statusCode: 200, contentType: "application/json");

        app.MapGet("/get/{id}", Get).Produces<SuperHero>();
        app.MapPost("/create", Create).AddEndpointFilter(async (ctx, next) => await Validate(ctx, next))
            .Accepts<SuperHero>("application/json")
            .Produces<SuperHero>(statusCode: 200, contentType: "application/json");
        app.MapPut("/update", Update).AddEndpointFilter(async (ctx, next) => await Validate(ctx, next))
              .Accepts<SuperHero>("application/json")
              .Produces<SuperHero>(statusCode: 200, contentType: "application/json");
        app.MapDelete("/delete/{id}", Delete);
    }
    
    ...

}

Declaration of validtion foreach superHero

public class SuperHeroValidator : AbstractValidator<SuperHero> 
{
    public SuperHeroValidator()
    {
        RuleFor(o => o.Name).NotNull().NotEmpty().MinimumLength(3).NotEqual("string");
        RuleFor(o => o.FirstName).NotNull().NotEmpty().MinimumLength(3).NotEqual("string");
        RuleFor(o => o.LastName).NotNull().NotEmpty().MinimumLength(3).NotEqual("string");
        RuleFor(o => o.Place).NotNull().NotEmpty().MinimumLength(3).NotEqual("string");
    }
}

public class SuperHeroDtoValidator : AbstractValidator<SuperHeroDto>
{
    public SuperHeroDtoValidator()
    {
        RuleFor(o => o.Name).NotNull().NotEmpty().MinimumLength(3).NotEqual("string");
        RuleFor(o => o.FirstName).NotNull().NotEmpty().MinimumLength(3).NotEqual("string");
        RuleFor(o => o.LastName).NotNull().NotEmpty().MinimumLength(3).NotEqual("string");
        RuleFor(o => o.Place).NotNull().NotEmpty().MinimumLength(3).NotEqual("string");
    }
}

Filter validator for checking currect parameters passed to endpoints

public class ValidationFilter<T> : IRouteHandlerFilter where T : class
{
    readonly IValidator<T> _validator;

    public ValidationFilter(IValidator<T> validator)
    {
        _validator = validator;
    }

    public async ValueTask<object> InvokeAsync(EndpointFilterInvocationContext context,
        EndpointFilterDelegate next)
    {
        var arg = context.Arguments.SingleOrDefault(p => p.GetType() == typeof(T));
        if (arg is null) return Results.BadRequest("The parameter is invalid.");

        var result = await _validator.ValidateAsync((T)arg);
        if (!result.IsValid)
        {
            var errors = string.Join(' ', result.Errors);
            return Results.Problem(errors);
        }

        return await next(context);
    }
}

Global Error Handling Using Middleware

IMiddleware approach -- Program.cs

builder.Services.AddTransient<GlobalExceptionHandlingMiddleware>();

...

app.UseMiddleware<GlobalExceptionHandlingMiddleware>();

Implemented function from IMiddleware interface - Defines middleware that can be added to the application's request pipeline.

 public async Task InvokeAsync(HttpContext context, RequestDelegate next)
{
    try
    {
        await next(context);
    }
    catch (Exception e)
    {
        _logger.LogError(e, e.Message);

        context.Response.StatusCode = (int)HttpStatusCode.InternalServerError;

        ProblemDetails problem = new()
        {
            Status = (int)HttpStatusCode.InternalServerError,
            Type = "Server error",
            Title = "Server error",
            Detail = "An internal server has occurred"
        };

        var json = JsonSerializer.Serialize(problem);

        await context.Response.WriteAsync(json);

        context.Response.ContentType = "application/json";
    }
}

superheroapi-postman's People

Contributors

bloodshop avatar

Watchers

 avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.