Thursday, 2 May 2024

Difference between IActionResult and ActionResult in asp.net core

 Please see the below example to understand difference between IActionResult and ActionResult<T>

For Specific type

public Thing Get() {
    return Context.Things.GetThing(1234);
}

This is OK if the action will always return one possible type. However, most actions may return exceptions (i.e. status codes other than 200) that have different types.

IActionResult type

This solves the above problem the IActionResult return type covers different return types.

public IActionResult Get() {
    Thing thing = Context.Things.GetThing(999);
    if (thing == null)

return NotFound(); else return

else return Ok(thing); }

For asynchronous action, use Task<IActionResult>:

public async Task<IActionResult> Get() {
    Thing thing = await Context.Things.GetThing(1234);
    if (thing == null)
        return NotFound();
    else
        return Ok(thing);
}

ActionResult type

ASP.NET Core 2.1 introduced the ActionResult<T> return type which offers the following benefits over the IActionResult type:

1- The action's expected return type is inferred from the T in ActionResult<T>. If you decorate your action with the [ProducesResponseType] attribute, you no longer need to explicitly specify its Type property. For example, you can simply use [ProducesResponseType(200)] instead of [ProducesResponseType(200, Type = typeof(Thing))].

2- T converts to ObjectResult, which means return new ObjectResult(T); is simplified to return T;.

public ActionResult<Thing> Get() {
    Thing thing = Context.Things.GetThing(1234);
    if (thing == null)
        return NotFound();
    else
        return thing;
}

For asynchronous action, use Task<ActionResult<T>>:

public async Task<ActionResult<Thing>> Get() {
    Thing thing = await Context.Things.GetThing(1234);
    if (thing == null)
        return NotFound();
    else
        return thing;
}

Sunday, 10 March 2024

Using Sqlite database with EF Core

 Sqlite is simple file based database; you just need to add reference of below packages in your API project and need to configure path to DB file.

Microsoft.EntityFrameworkCore

Microsoft.EntityFrameworkCore.Design

Microsoft.EntityFrameworkCore.Sqlite

Microsoft.EntityFrameworkCore.Tools














Once you will create DBContext, you need to create migration and need to update database, below are CLI commands for the same.

1. dotnet ef migrations add Name_Of_Migration

2. dotnet ef database update

Note: No need to create sqlite db file separately once we will update database with migration it will automatically create DB file.





SQLite DB file path in ASP.Net Core application

 I was facing issue to provide file path in EF Core DBContext connection string, after struggling for a while I was successfully able to connect to DB.



Sunday, 2 May 2021

Asp.Net Core : How to check route metadata, endpoint details?

 

To Check route metadata, you can use the following code and debug it.

app.Use(async (context, next) =>
{
 var endPoint = context.GetEndpoint();
 var routes = context.Request.RouteValues;
});

Wednesday, 31 March 2021

Responsibility of asp.net core mvc controller

 

Controller class has responsibility to respond incoming request URL by invoking appropriate action method. Controller chooses appropriate model or retrieves data from data source and passes this data to appropriate View template which generates HTML, controller sends this html response back to the caller/ user.

In other words, controller invokes appropriate action from requested URL, selects/generates data and sends this data to view, view renders data and generates appropriate HTML and Controller sends response back to the client.

Thursday, 25 March 2021

What is an Http endpoint ?

 

In simple words, It's a URL in a web application/Api like ("https://www.mysite.com/home"  or "https://localhost:5001/Account/index" ).

Basically it's a combination of 

  •                 Network protocol (like http/https, etc.).
  •                 Server address and port (like localhost:5001, etc.)
  •                 URI (to uniquely identify a resource like account/index, etc.)


Friday, 10 April 2020

ASP.NET CORE : Version specific swagger document for Web Api Core [ using asp.net core 3.0 ]


Objective : We have versioned our Web APi and want to create swagger /OpenAPI documentation version specific. i.e. when user will select specific version he would be able to see api specific to selected version.

Versioning for API is easy using ASP.NET core's inbuilt middle ware. I have created a separate post related to API versioning. This post is specific to creation of version specific swagger document.

Nuget Packages : below are the list of Nuget packages needed to implement versioning and Swagger documentation in the application.

Microsoft.AspNetCore.Mvc.Version : To implement versioning.

Microsoft.AspNetCore.Mvc.Versioning.ApiExplorer: Used by swagger to generate version specific document.

Swashbuckle.AspNetCore.Swagger : Swagger middleware exposes json endpoint.

Swashbuckle.AspNetCore.SwaggerGen : Generates JSON file

Swashbuckle.AspNetCore.SwaggerUI : Generates interactive UI documentation for API.

Now, we will see code which we have to add in ConfigureServices and Configure methods:

Need  to add below services to implement inbuilt versioning functionality:

            services.AddApiVersioning(o =>
            {
                o.AssumeDefaultVersionWhenUnspecified = true;
                o.DefaultApiVersion = new ApiVersion(1, 0);
            });   // inbuilt versioning implementation

            services.AddVersionedApiExplorer(); // swagger versioning specific

// above code is required to implement versioning. below code is required for swagger documentation.

services.AddSwaggerGen(
    options =>
    {
                    
        var provider = services.BuildServiceProvider().GetRequiredService<IApiVersionDescriptionProvider>();
        // add a swagger document for each discovered API version
        foreach (var description in provider.ApiVersionDescriptions)
        {
            options.SwaggerDoc(description.GroupName, new OpenApiInfo { Version = description.ApiVersion.ToString(),
                                                                        Description ="Sample API version: "+ description.GroupName ,
                                                                        Title="API Versioning Sample"
                                                                      });
        }
        var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
        var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);
        Console.WriteLine("***************************** " + xmlPath);
        options.IncludeXmlComments(xmlPath);
    });

We need to add below code in Configure method to enable swagger documentation :

  app.UseSwagger();
            app.UseSwaggerUI(
                options =>
                {
                    var provider = app.ApplicationServices.GetRequiredService<IApiVersionDescriptionProvider>();
                    foreach (var description in provider.ApiVersionDescriptions)
                    {
                        options.SwaggerEndpoint( $"/swagger/{description.GroupName}/swagger.json",description.GroupName.ToUpperInvariant());
                    }
                });

Now we have to add APIVersion Attribute on Controller /Action methods. like :

    /// <summary>
    /// this is sample api for version 1.0
    /// </summary>
    [ApiVersion("1.0")]
    [ApiController]
    [Route("api/v{version:apiVersion}/[controller]")]
    public class EmployeeController : ControllerBase
    {
        /// <summary>
        /// Get api for version 1.0
        /// </summary>
        [HttpGet]
        public IActionResult Get()
        {
            return Ok(" Hello from v1");
        }
    }
 
    /// <summary>
    /// this is sample api for version 2.0
    /// </summary>
    [ApiVersion("2.0")]
    [ApiController]
    [Route("api/v{version:apiVersion}/[controller]")]
    public class Employee2Controller : ControllerBase
    { /// <summary>
      /// Get api for version 2.0
      /// </summary>
      ///
      [HttpGet]
        public IActionResult Get()
        {
            return Ok(" Hello from v2");
        }
    }

[Copy paste above code  in editor for better readability/understanding]

Some important point to remember:

1. Make sure that each action method is decorated with proper get/post attribute.
2. Route is specified for each action method.
3. Xml comments are added for each action method.
4. Go to project Properties->build->check-Xml document file. ( if you are using xml comments in swagger)




Resource :
https://github.com/domaindrivendev/Swashbuckle.AspNetCore/blob/master/README.md#list-multiple-swagger-documents

How to create and use middleware in asp.net core

Middleware is piece of code that's assembled into an app pipeline to handle requests and responses.  Each middleware component in the re...