Using vs2022 in ASP Net core

Time:2022-5-4

In ASP When dealing with web applications in. Net core, we may often want to build lightweight services, that is, services without templates or controller classes.

Lightweight services can reduce resource consumption and improve performance. We can create these lightweight services or APIs in startup or program classes.

1. Use vs2022 to create ASP Net core project

We created an asp.net in Visual Studio 2022 Net core project. Follow these steps to create a new asp.net in Visual Studio 2022 Net core web API 6 project.

  • 1) Start the visual studio 2022 ide.
  • 2) Click create new project.
  • 3) In the create new project window, select asp.net core web API from the list of templates displayed.
  • 4) Click next.
  • 5) In the configure your new project window, specify the name and location of the new project.
  • 6) According to your preference, you can select the “place solution and project in the same directory” check box.
  • 7) Click next.
  • 8) In the “additional information” window displayed next, select from the drop-down list at the top Net 6.0 as the target framework. Leave authentication type as none (default).
  • 9) Make sure the “enable docker”, “configure for HTTPS” and “enable open API support” check boxes are not selected, as we will not use any of these features here. You can also choose to uncheck the “use controllers” check box because we will create our own controllers.
  • 10) Click create.

This will create a new asp.net in Visual Studio 2022 Net core 6 web API project. We will use this project in subsequent parts of this article to illustrate how to use lightweight services.

In asp.2 Net core enables a lightweight service

Since we will build lightweight services that do not require controllers, we should delete the controllers solution folder and any model classes created by default.

Next, open launchsettings.com under the properties solution folder JSON file, delete or comment out the launchurl key value pair, as shown in the code given below.

Where launchurl refers to the host of the application. When the application starts, the URL specified in the launchurl is used to start the application.

If the URL is wrong or does not exist, the application will throw an error at startup. By removing the launchurl or commenting it out, we can ensure that the application does not use the default launchurl to start the application, thus avoiding any errors. Once the launchurl is deleted, the application will return to port 5000.


"profiles": {
    "Light_Weight_Services": {
        "commandName": "Project",
        "dotnetRunMessages": true,
        "launchBrowser": true,
        //"launchUrl": "",
        "applicationUrl": "http://localhost:5000",
        "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development"
        }
    },
    "IIS Express": {
        "commandName": "IISExpress",
        "launchBrowser": true,
        //"launchUrl": "",
        "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development"
        }
    }

3. In ASP Net core using iendpointconventionbuilder extension method

We can use some extension methods of the iendpointconventionbuilder interface to map requests.

The following is a list of these extension methods:

  • MapGet
  • MapPost
  • MapDelete
  • MapPut
  • MapRazorPages
  • MapControllers
  • MapHub
  • MapGrpcServices

The mapget, mappost, mapdelete, and mapput methods are used to delegate requests to the routing system. Maprazorpages is used for razorpages, mapcontrollers is used for controllers, maphub is used for signalr, and mapgrpcservice is used for grpc.

The following code explains how to use mapget to create an HTTP get endpoint.


endpoints.MapGet("/", async context =>
{
     await context.Response.WriteAsync("Hello World!");
});

We create a c# file named author, which contains the following code:


public class Author
{
    public int Id { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
}

Create a read-only list of authors and fill in some data, as shown below:


private readonly List<Author> _authors;
    public Startup(IConfiguration configuration)
    {
        _authors = new List<Author>
        {
            new Author
            {
                Id = 1,
                FirstName = "Joydip",
                LastName = "Kanjilal"
            },
            new Author
            {
                Id = 2,
                FirstName = "Steve",
                LastName = "Smith"
            },
            new Author
            {
                Id = 3,
                FirstName = "Julie",
                LastName = "Lerman"
            }
        };
        Configuration = configuration;
    }

We can use the following code to create another endpoint and return the author list in JSON format.


endpoints.MapGet("/authors", async context =>
{
        var authors = _authors == null ? new List<Author>() : _authors;
        var response = JsonSerializer.Serialize(authors);
        await context.Response.WriteAsync(response);
});

4. In ASP Net core using lightweight services to retrieve records

To retrieve a specific record by ID, we can write the following code:


endpoints.MapGet("/authors/{id:int}", async context =>
{
    var id = int.Parse((string)context.Request.RouteValues["id"]);
    var author = _authors.Find(x=> x.Id == id);
    var response = JsonSerializer.Serialize(author);
    await context.Response.WriteAsync(response);
});

5. In ASP Net core using lightweight services to create records

To add data using HTTP post, we can use the mappost extension method, as shown below:


endpoints.MapPost("/", async context =>
{
    var author = await context.Request.ReadFromJsonAsync<Author>();
    _authors.Add(author);
    var response = JsonSerializer.Serialize(author);
    await context.Response.WriteAsync(response);
});

6. In ASP Net core using lightweight services to delete records

To delete data, we can use the mapdelete extension method, as shown below:


endpoints.MapDelete("/authors/{id:int}", async context =>
{
    var id = int.Parse((string)context.Request.RouteValues["id"]);
    var author = _authors.Find(x => x.Id == id);
    _authors.Remove(author);
    var response = JsonSerializer.Serialize(_authors);
    await context.Response.WriteAsync(response);
});

7. ASP. Configuration method of lightweight service in net core

The following is the complete source code of the configure method of the startup class:


public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }
    app.UseRouting();
    app.UseAuthorization();
    app.UseEndpoints(endpoints =>
    {
        endpoints.MapGet("/", async context =>
        {
            await context.Response.WriteAsync("Hello World!");
        });
        endpoints.MapGet("/authors", async context =>
        {
            var authors = _authors == null ? new List<Author>() : _authors;
            var response = JsonSerializer.Serialize(authors);
            await context.Response.WriteAsync(response);
        });
        endpoints.MapGet("/authors/{id:int}", async context =>
        {
            var id = int.Parse((string)context.Request.RouteValues["id"]);
            var author = _authors.Find(x=> x.Id == id);
            var response = JsonSerializer.Serialize(author);
            await context.Response.WriteAsync(response);
        });
        endpoints.MapPost("/", async context =>
        {
            var author = await context.Request.ReadFromJsonAsync<Author>();
            _authors.Add(author);
            var response = JsonSerializer.Serialize(author);
            await context.Response.WriteAsync(response);
        });
        endpoints.MapDelete("/authors/{id:int}", async context =>
        {
            var id = int.Parse((string)context.Request.RouteValues["id"]);
            var author = _authors.Find(x => x.Id == id);
            _authors.Remove(author);
            var response = JsonSerializer.Serialize(_authors);
            await context.Response.WriteAsync(response);
        });
    });
}

8. In ASP Net core to create lightweight services in the program class

In ASP Net 6, there is another way to create lightweight services. We created a new ASP When net core 6 is an empty project, startup is not created by default CS file. Therefore, we can CS file to create lightweight services.

The following example shows how to do this:

app.MapGet("/", () => "Hello World!");
app.MapDelete("/{id}", (Func<int, bool>)((id) => {
    //Delete record code
    return true;
}));
    app.MapPost("/", (Func<Author, bool>)((author) => {
    //Add record code
    return true;
}));
app.Run();

Lightweight services or APIs have no templates and do not require controller classes to create them.

We can create such services in the startup or program class.

If we want to implement authorization in lightweight services, we can use the requireauthorization extension method of iendpointconventionbuilder interface.

reference material:

Programming treasure house​​

C# programming

The above is a small series to introduce to you, using vs2022 in ASP Net core to build lightweight services, we hope to help. Thank you very much for your support to the developeppaer website!

Recommended Today

IOS imitates various ways of wechat long press to identify QR code

Reference:https://github.com/nglszs/BCQRcode Mode 1: #import <UIKit/UIKit.h> @interface ViewController : UIViewController @end ************** #import “ViewController.h” @interface ViewController () @end @implementation ViewController – (void)viewDidLoad { [super viewDidLoad]; self. Title = @ “QR code”; UIBarButtonItem *leftBtn = [[UIBarButtonItem alloc] Initwithtitle: @ “build” style:UIBarButtonItemStylePlain target:self action:@selector(backView)]; self.navigationItem.leftBarButtonItem = leftBtn; UIBarButtonItem *rightBtn = [[UIBarButtonItem alloc] Initwithtitle: @ “scan” style:UIBarButtonItemStylePlain target:self action:@selector(ScanView)]; […]