1
头图

FastEndpoints is an open source webapi framework developed based on .NET 6. It can be a good substitute for .NET Minimal APIs and MVC. It is specially designed for development efficiency and brings a new development mode and coding experience. In addition, .NET middleware, authentication, authorization, logging, and dependency injection are also supported, and some are even enhanced, so you can get started with it soon.


Researcher at Microsoft MVP Labs
image.png
图片

Small scale chopper

Next, I'll create a webapi application with FastEndpoints to show how it's used, it's really easy.

  • Create a new project
    dotnet new web -n MyWebApp
  • enter the project
    cd MyWebApp
  • Install Nuget packages
    dotnet add package FastEndpoints
  • Update Program.cs

     global using FastEndpoints;
    
    var builder=WebApplication.CreateBuilder();
    builder.Services.AddFastEndpoints();
    
    var app = builder.Build();
    app.UseAuthorization();
    app.UseFastEndpoints();
    app.Run();
  • Add a Request DTO

     public class MyRequest
    {
      public int Age { get; set; }
      public string Name { get; set; }
    }
  • Add a Response DTO

     public class MyResponse
    {
      public int Id { get; set; }
      public int Age { get; set; }
    
      public string Name { get; set; }
    
      public DateTime CreateTime { get; set; }
    }
  • Add an Endpoint Class
    Then add the following code, this is where the business logic is handled

     public class MyEndpoint : Endpoint<MyRequest>
    {
      public override void Configure()
    {
          Post("/api/user/create");
          AllowAnonymous();
      }
    
      public override async Task HandleAsync(MyRequest req, CancellationToken ct){
          var response = new MyResponse()
          {
              Id = 1,
              Age = req.Age,
              Name = req.Name,
              CreateTime = DateTime.Now
           };
          await SendAsync(response);
      }
    }

    All the preparations are ready, let's start our webapi project directly.
    Then use Postman or other tools to send a POST request to the /api/user/create endpoint.

图片

Created a user, and returned user information, it's that simple, this is FastEndpoints.

You may have noticed the Configure() method above, specifying the Http verb and endpoint. Of course, you can also use .NET native features, which are also supported.

 [HttpPost("/my-endpoint")]
[Authorize(Roles = "Admin,Manager")]
public class UpdateAddress : Endpoint<MyRequest, MyResponse>
{
    public override async Task HandleAsync(MyRequest req, CancellationToken ct){
        await SendAsync(new MyResponse { });
    }
}

dependency injection

In FastEndpoints, there are three ways to access services registered in the IOC container.
Suppose we have a HelloWorldService.

 public interface IHelloWorldService
{
    string SayHello();
}

public class HelloWorldService : IHelloWorldService
{
    public string SayHello() => "hello world!";
}

And registered to the IOC container.

 builder.Services.AddScoped<IHelloWorldService, HelloWorldService>();

▌Constructor injection

This is the method we are most familiar with and use the most.

 public class MyEndpoint : EndpointWithoutRequest
{
    private IHelloWorldService _helloService;

    public MyEndpoint(IHelloWorldService helloScv)
    {
        _helloService = helloScv;
    }

    public override void Configure()
    {
        Get("/api/hello-world");
    }

    public override async Task HandleAsync(CancellationToken ct)
    {
        await SendAsync(_helloService.SayHello());
    }
}

▌Property injection

Service instances can be automatically injected through properties.

 public class MyEndpoint : EndpointWithoutRequest
{
    public IHelloWorldService HelloService { get; set; }
    public override void Configure()
    {
        Get("/api/hello-world");
    }

    public override async Task HandleAsync(CancellationToken ct)
    {
        await SendAsync(HelloService.SayHello());
    }
}

▌ Manual parsing

You can also get the service manually as follows.
Use the TryResolve or Resolve() methods.

 public override async Task HandleAsync(CancellationToken ct)
{
    IHelloWorldService? helloSvc = TryResolve<IHelloWorldService>();

    if (helloSvc is null)
        ThrowError("service not resolved!");

    var logger = Resolve<ILogger<MyEndpoint>>();
    logger.LogInformation("hello service is resolved...");
    await SendAsync(helloSvc.SayHello());
}
  • pre-parsed services

The three services below are pre-parsed and we can use them directly in the handler.

 property: Config
service : IConfiguration

property: Env
service : IWebHostEnvironment

property: Logger
service : ILogger

It is very convenient to use them.

 public override async Task HandleAsync(CancellationToken ct)
{
    Logger.LogInformation("this is a log message");
    var isProduction = Env.IsProduction();
    var smtpServer = Config["SMTP:HostName"];
    ...
}

architectural pattern

If you've written about the Go Web, you'll see how similar this is.

 package main

import (
    "fmt"
    "net/http"
)

func main() {
    http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
        fmt.Fprintf(w, "Hello, you've requested: %s\n", r.URL.Path)
    })

    http.ListenAndServe(":80", nil)
}

FastEndpoints follows the REPR design (Request-Endpoint-Response), which is different from the MVC pattern we often say.

Think about it, if the backend is just a webapi application without View, then it becomes the MC architecture. Isn't it weird, so why not use REPR mode?

On the other hand, "layered architecture" is something we are familiar with and use frequently, where code is divided into different layers.

The benefits of this are also obvious. They are combined in a decoupled way, and we can easily replace the layers when needed.
图片
There is also an architecture called "vertical slice architecture", where each component of the system is a separate piece and does not affect each other, just like microservices.
图片
FastEndpoints uses the following "vertical slice architecture".

Summarize

As you can see, FastEndpoints is a flexible and efficient webapi framework. In addition it has other features like exception handling, integration and unit testing, throttling, API versioning and more.

Hope it works for you!

Click here for related documents
Click here for Github content


Microsoft Most Valuable Professional (MVP)

图片
The Microsoft Most Valuable Professional is a global award given to third-party technology professionals by Microsoft Corporation. For 29 years, technology community leaders around the world have received this award for sharing their expertise and experience in technology communities both online and offline.

MVPs are a carefully selected team of experts who represent the most skilled and intelligent minds, passionate and helpful experts who are deeply invested in the community. MVP is committed to helping others and maximizing the use of Microsoft technologies by Microsoft technical community users by speaking, forum Q&A, creating websites, writing blogs, sharing videos, open source projects, organizing conferences, etc.

For more details, please visit the official website:
https://mvp.microsoft.com/en-us


Click here to join Microsoft MVP now~


微软技术栈
423 声望995 粉丝

微软技术生态官方平台。予力众生,成就不凡!微软致力于用技术改变世界,助力企业实现数字化转型。