What are the difference using app run and app useendpoints in asp net core

Understanding the Difference between app.Run and app.UseEndpoints in ASP.NET Core

When web applications ASP.NET Core, you may come across two methods: app.Run and app.UseEndpoints. These methods are used to configure the request pipeline in your application. they may seem similar at first glance, there are some key differences between them that you should be aware of.

app.Run

The app.Run method is used to handle a request directly. It a delegate that represents a middleware component responsible for processing the request and generating a . This method is typically used for simple scenarios where you want to handle a specific request and return a response immediately.

Here's an example of how you can use app.Run to handle a request:


app.Run(async () =>
{
    await context.Response.WriteAsync("Hello, World!");
});

In this example, whenever a request is , the delegate passed to app.Run will be executed. It simply writes “Hello, World!” as the response.

app.UseEndpoints

The app.UseEndpoints method, on the other hand, is used to define the endpoints of your application. An endpoint represents a specific URL that the application can handle. It allows you to map incoming requests to specific actions or controllers in your application.

Here's an example of how you can use app.UseEndpoints to define endpoints:


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

In this example, we are mapping the root URL (“/”) to a delegate that writes “Hello, World!” as the response. This means that whenever a request is made to the root URL, the delegate will be executed.

When to Use app.Run vs app.UseEndpoints

Now that we understand the differences between app.Run and app.UseEndpoints, let's discuss when to use each method.

Use app.Run when:

  • You want to handle a specific request directly.
  • You want to return a response immediately further processing.
  • You have simple scenarios that don't require or controller actions.

Use app.UseEndpoints when:

  • You want to define multiple endpoints for your application.
  • You want to use routing to map incoming requests to specific actions or controllers.
  • You have more complex scenarios that require advanced routing capabilities.

By understanding the differences between app.Run and app.UseEndpoints, you can make informed decisions on how to configure the request pipeline in your ASP.NET Core application.

Rate this post

Leave a Reply

Your email address will not be published. Required fields are marked *

Table of Contents