Tuesday, 11 February 2025

Swagger substitutes and open API documentation in.NET 9

Leave a Comment

For creating OpenAPI documents in ASP.NET Core applications, the Microsoft.AspNetCore.OpenApi package provides integrated support. It offers a number of essential features to improve API documentation. It first makes it possible for OpenAPI documents to be generated during runtime, which developers may then access via a specific application endpoint. Furthermore, it incorporates "transformer" APIs, which offer the ability to alter the produced documentation as necessary. Additionally, the package facilitates the generation of many OpenAPI documents from a single application, which facilitates the effective management and organization of API specifications. 


In this article, we will understand the following concepts in detail.

  • Simple .Net Core Web API Project
  • Understanding about Open API dcoumentation
  • Swagger UI inclusion
  • ReDoc Open API
  • Scalar Open API

Simple .NET Core Web API Project

We will create a simple .Net core Web API project with the following steps in Visual Studio 2022.

Open Visual Studio 2022, Click on "Create new Project" then select the "ASP.NET Core Web API" option and click on "Next". 

Enter the project named "OpenAPIDocDemo" in the preferred location like below and click on "Next".


The Additional Information window is shown below. for this simple demo, we are keeping the info as-is and then clicking on the "Create" button.

After clicking on the "Create" button it shows the project like below.


We are done with a simple .Net Core Web API project.

Understanding about OpenAPI documentation

In the created project, we can observe the following referenced package "Microsoft.AspNetCore.OpenApi" provides built-in support of OpenAPI documentation.

 The Program.cs file has the following highlighted information about OpenAPI support.

Let's run the project and append the following "openapi/v1.json" in the browser localhost URL (Ex: localhost:7158/openapi/v1.json). We can observe the following screen.

It indicates without doing even a small line of code changes, The.NET9 Web API supports/generates JSON documents with the standard format of API documentation.

Swagger UI Inclusion

Let's make very minimal changes in this demo project to include Swagger UI (our very owned habituated API documentation.

Install the following package, "Swashbuckle.AspNetCore.SwaggerUI" from Nuget.


Add the following lines of code to the Program.cs file below to the existing code line "app.MapOpenApi();"
app.UseSwaggerUI(options =>
{
    options.SwaggerEndpoint("/openapi/v1.json", "v1");
});

That's it. We are done with Swagger UI inclusion in our .NET API project. Let's run the project again with the sample URL (https://localhost:7158/swagger/index.html). We can see the following page.



ReDoc UI Open API Document

Let's try to include ‘ReDoc” API documentation as well in our project.

Install the following Nuget package “Swashbuckle.AspNetCore.ReDoc”


 Add the following lines of code to the Program.cs file.

app.UseReDoc(options =>
{
    options.SpecUrl("/openapi/v1.json");
});

It's that simple..!!. We just included ReDoc API documentation in our .NET API project. Let's run the project again with the sample URL (https://localhost:7158/api-docs/index.html). We can see the following page.

Scalar UI Open API Document

Let's include ‘Scalar UI” Open API documentation in our project as well.

Add the following Nuget package “Scalar.AspNetCore” to our project.

Add the following simple line of code to our Program.cs file.
app.MapScalarApiReference();
So, After the inclusion of all aforesaid Open API document-related code inclusions in the Program.cs file, the code looks like below.
using Scalar.AspNetCore;
var builder = WebApplication.CreateBuilder(args);
// Add services to the container
builder.Services.AddControllers();
builder.Services.AddOpenApi(); 
var app = builder.Build();
// Configure the HTTP request pipeline
if (app.Environment.IsDevelopment())
{
    app.MapOpenApi();

    app.UseSwaggerUI(options =>
    {
        options.SwaggerEndpoint("/openapi/v1.json", "v1");
    });
}
app.UseReDoc(options =>
{
    options.SpecUrl("/openapi/v1.json");
});

app.MapScalarApiReference();

app.UseHttpsRedirection();
app.UseAuthorization();
app.MapControllers();
app.Run();

Let's run our project with the sample URL (https://localhost:7158/scalar/), and the screen looks like the one below.

The Scalar API provides more GUI-friendly features with the support of multiple programming languages of sample code if needed. These are really helpful whenever other development teams try to include/call our API in an easy way.

Let's try for a sample C# code for one of our existing Get methods in this sample project in the following way.

Best ASP.NET Core 8.0.11 Hosting Recommendation

One of the most important things when choosing a good ASP.NET Core 8.0.11 hosting is the feature and reliability. HostForLIFE is the leading provider of Windows hosting and affordable ASP.NET Core, their servers are optimized for PHP web applications. The performance and the uptime of the hosting service are excellent and the features of the web hosting plan are even greater than what many hosting providers ask you to pay for. 

At HostForLIFE.eu, customers can also experience fast ASP.NET Core hosting. The company invested a lot of money to ensure the best and fastest performance of the datacenters, servers, network and other facilities. Its datacenters are equipped with the top equipments like cooling system, fire detection, high speed Internet connection, and so on. That is why HostForLIFEASP.NET guarantees 99.9% uptime for ASP.NET Core. And the engineers do regular maintenance and monitoring works to assure its Orchard hosting are security and always up.

Read More...

Tuesday, 4 February 2025

ASP.NET Core 6: Using Sessions to Create Dynamic Menus in Layout Pages

Leave a Comment

This article demonstrates how you leverage session management in ASP.NET Core 6. 1 to save and display dynamic menus on the layout page, allowing each user to have a personalized navigation experience. Session Enablement in Program.cs


Configuring the session in the Program.cs file in ASP.NET Core 6 requires adding the AddSession and UseSession methods to the pipeline. The following code will activate the session.

builder.Services.AddSession(options =>
{
    options.IdleTimeout = TimeSpan.FromMinutes(30);
    options.Cookie.HttpOnly = true;
});

builder.Services.AddSession();

2. Define the Menu Model

To show the menu's structure, you require a model. This is a simple model that includes Submodule and ModuleSubmoduleRolePermission.

public class ModuleSubmoduleRolePermission
{
    public int ModuleId { get; set; }
    public string ModuleName { get; set; }
    public string Action { get; set; }
    public bool IsChecked { get; set; }
    public List<SubmodulePermission> Submodules { get; set; }
}

public class SubmodulePermission
{
    public int? SubmoduleId { get; set; }
    public string SubmoduleName { get; set; }
    public string Controller { get; set; }
    public string subAction { get; set; }
    public string RoleName { get; set; }
    public int? RoleId { get; set; }
    public bool IsChecked { get; set; }
}

3. Store Menu Data in Session

Serialize the menu data in your controller and save it in the session. This is an example of an action method.

[HttpPost]
public async Task<ActionResult> Login(LoginModel model)
{
    if (ModelState.IsValid)
    {
        var response = await _authService.LoginAsync(model);
        if (response.Success == true) // Assuming "1" indicates success
        {
            var token = response.Token;
            Response.Cookies.Append("authToken", token, new CookieOptions
            {
                HttpOnly = true, // Prevent JavaScript access to the cookie
                Secure = true,   // Only send cookie over HTTPS
                SameSite = SameSiteMode.Strict // Prevent CSRF attacks

            });
            var handler = new JwtSecurityTokenHandler();
            var jsonToken = handler.ReadToken(token) as JwtSecurityToken;
            var userRole = jsonToken?.Claims.FirstOrDefault(c => c.Type == "role")?.Value;
            var Module = await _authService.GetModulesByRoleAsync(token,userRole);
            HttpContext.Session.SetString("Modules", JsonConvert.SerializeObject(Module));
            // If login is successful, redirect to another action (e.g., Dashboard)
            return RedirectToAction("Dashboard", "Dashboard");
        }
        else
        {
            // If login failed, show the error message from StatusDesc
            ViewBag.ErrorMessage= response.Message;
        }
    }

    // If we got this far, something failed; redisplay the form
    return View(model);
}

4. Retrieve and Display Menu in _Layout.cshtml

You can dynamically render the menu and access the session data on the layout page. To retrieve session values, use IHttpContextAccessor; to deserialize the data, use JsonConvert.

@inject IHttpContextAccessor HttpContextAccessor
@using ModelsLibrary.ADOModel
@using Newtonsoft.Json

@{
    var modulesJson = HttpContextAccessor.HttpContext?.Session.GetString("Modules");
    var UserName = HttpContextAccessor.HttpContext?.Session.GetString("username");
    List<ModuleSubmoduleRolePermission> modules = new();

    if (!string.IsNullOrEmpty(modulesJson))
    {
        modules = JsonConvert.DeserializeObject<List<ModuleSubmoduleRolePermission>>(modulesJson);
    }
}

5. Retrieve Menu Data

<div class="sidebar-nav">
    <!--navigation-->
   <ul class="hflmenu" id="sidenav">

        @if (modules != null)
        {
            @foreach (var module in modules)
            {
                <li>
                    <a href="@(string.IsNullOrEmpty(module.Action) ? "javascript:;" : GetUrl(module.Action))"
                       class="@(module.Submodules != null ? "has-arrow" : "")">
                        <div class="parent-icon">
                            <i class="material-icons-outlined">@GetIconForModule(module.ModuleName)</i>
                        </div>
                        <div class="menu-title">@module.ModuleName</div>
                    </a>

                    @if (module.Submodules != null)
                    {
                        <ul>
                            @foreach (var submodule in module.Submodules)
                            {
                                <li>
                                    <a href="@GetUrl(submodule.subAction)">
                                        <i class="material-icons-outlined">arrow_right</i>
                                        @submodule.SubmoduleName
                                    </a>
                                </li>
                            }
                        </ul>
                    }
                </li>
            }

        }
        else
        {
            <p>No modules available</p>

        }

    </ul>
    <!--end navigation-->
</div>

Output


Conclusion
The user experience in web applications can be enhanced by using this method to dynamically create a customized navigation menu based on session data in ASP.NET Core 6. You can do this by storing menu items in the session and using them in your layout to render dynamic menus that reflect the user's role or context.

Best ASP.NET Core 8.0.11 Hosting Recommendation

One of the most important things when choosing a good ASP.NET Core 8.0.11 hosting is the feature and reliability. HostForLIFE is the leading provider of Windows hosting and affordable ASP.NET Core, their servers are optimized for PHP web applications. The performance and the uptime of the hosting service are excellent and the features of the web hosting plan are even greater than what many hosting providers ask you to pay for. 

At HostForLIFE.eu, customers can also experience fast ASP.NET Core hosting. The company invested a lot of money to ensure the best and fastest performance of the datacenters, servers, network and other facilities. Its datacenters are equipped with the top equipments like cooling system, fire detection, high speed Internet connection, and so on. That is why HostForLIFEASP.NET guarantees 99.9% uptime for ASP.NET Core. And the engineers do regular maintenance and monitoring works to assure its Orchard hosting are security and always up.

 

Read More...

Tuesday, 21 January 2025

Working with the .NET 8 gRPC API

Leave a Comment

We'll examine a contemporary API architecture today. Using.NET C#, we will create a basic gRPC service that carries out CRUD (Create, Read, Update, Delete) actions.

gRPC is a modern, open-source, high-performance Remote Procedure Call (RPC) framework that can run in any environment. It enables client and server applications to communicate transparently and simplifies the building of connected systems. gRPC is based on the idea of defining a service and specifying the methods that can be called remotely with their parameters and return types. On the server side, the server implements this interface and runs a gRPC server to handle client calls. On the client side, the client has a stub that provides the same methods as the server.


gRPC is designed to work with a variety of programming languages, making it an ideal choice for multi-language systems. It uses Protocol Buffers (protobuf) as its Interface Definition Language (IDL) and its underlying message interchange format, which is a powerful binary serialization toolset and language.

History of gRPC

gRPC was initially created by Google and is a part of the Cloud Native Computing Foundation (CNCF). It was publicly announced in February 2015 and has evolved from the earlier Stubby, an RPC system that Google developed internally to connect their large-scale microservices.

One of the main reasons for developing gRPC was to address the need for efficient communication in microservices architectures where lightweight data exchange is crucial. gRPC's use of HTTP/2 as the transport protocol allows for features like concurrently streaming data in both directions, multiplexing multiple requests over a single connection, header compression, etc.

The evolution of gRPC is marked by its adoption across various organizations outside Google for both internal microservices communication and client-facing APIs. It supports several languages and platforms, providing developers with a versatile tool for building distributed systems.

Prerequisites

  • Visual Studio 2019 or later with the ASP.NET and web development workload.
  • .NET 5.0 SDK or later.
  • A basic understanding of gRPC.

Step 1. Set up the .NET Core gRPC Project

  1. Open Visual Studio.
  2. Click on "Create a new project."
  3. Search for the "gRPC Service" template and select it. Click "Next."
  4. Name the project BookGrpcService and the solution BookGrpcService. Click "Create."

Step 2. Define the Proto File

Create or update the Protos/book.proto file. This protocol buffer file defines the structure of the gRPC service and the messages that are exchanged.

syntax = "proto3";
option csharp_namespace = "BookGrpcService";
package book;
// The Book service definition
service Books {
  rpc CreateBook (CreateBookRequest) returns (Book);
  rpc GetBook (GetBookRequest) returns (Book);
  rpc UpdateBook (UpdateBookRequest) returns (Book);
  rpc DeleteBook (DeleteBookRequest) returns (DeleteBookResponse);
  rpc ListBooks (ListBooksRequest) returns (ListBooksResponse); // Adding this line
}
// The request message containing the ID
message GetBookRequest {
  int32 id = 1;
}
// The request message containing the book details
message CreateBookRequest {
  string title = 1;
  string author = 2;
}
// The request message containing full book information
message UpdateBookRequest {
  int32 id = 1;
  string title = 2;
  string author = 3;
}
// The request message for deleting book by ID
message DeleteBookRequest {
  int32 id = 1;
}
// The response message containing status
message DeleteBookResponse {
  string status = 1;
}
message ListBooksRequest {}
message ListBooksResponse {
  repeated Book books = 1; // A list of books
}
// The message representing a Book
message Book {
  int32 id = 1;
  string title = 2;
  string author = 3;
}

Step 3. Implement the Service in C#

create a new service implementation in Services/BookService.cs that supports CRUD operation based on the Proto file.

using Grpc.Core;
using System.Collections.Generic;
using System.Threading.Tasks;
using BookGrpcService;
namespace BookGrpcService.Services
{
    public class BooksService : Books.BooksBase
    {
        private static readonly List<Book> books = new List<Book>
        {
            new Book { Id = 1, Title = "1984", Author = "George Orwell" },
            new Book { Id = 2, Title = "Brave New World", Author = "Aldous Huxley" },
            new Book { Id = 3, Title = "To Kill a Mockingbird", Author = "Harper Lee" }
        };
        private static int nextId = 4;
        public override Task<Book> CreateBook(CreateBookRequest request, ServerCallContext context)
        {
            var book = new Book
            {
                Id = nextId++,
                Title = request.Title,
                Author = request.Author
            };
            books.Add(book);
            return Task.FromResult(book);
        }
        public override Task<Book> GetBook(GetBookRequest request, ServerCallContext context)
        {
            var book = books.Find(b => b.Id == request.Id);
            return Task.FromResult(book);
        }
        public override Task<ListBooksResponse> ListBooks(ListBooksRequest request, ServerCallContext context)
        {
            ListBooksResponse response = new ListBooksResponse();
            response.Books.AddRange(books);
            return Task.FromResult(response);
        }
        public override Task<Book> UpdateBook(UpdateBookRequest request, ServerCallContext context)
        {
            var book = books.Find(b => b.Id == request.Id);
            if (book != null)
            {
                book.Title = request.Title;
                book.Author = request.Author;
            }
            return Task.FromResult(book);
        }
        public override Task<DeleteBookResponse> DeleteBook(DeleteBookRequest request, ServerCallContext context)
        {
            var book = books.Find(b => b.Id == request.Id);
            if (book != null)
            {
                books.Remove(book);
                return Task.FromResult(new DeleteBookResponse { Status = "Deleted" });
            }
            return Task.FromResult(new DeleteBookResponse { Status = "Book Not Found" });
        }
    }
}

Step 4. Regenerate the gRPC code

Ensure to rebuild the project to regenerate the C# gRPC code automatically.

Step 5. Testing the Service

Run the project in Visual Studio by hitting F5. Use a gRPC client tool like BloomRPC gRPC URL or PostMan to test each service operation by sending the respective requests.

Testing in Postman

Open the Postman, click on New, and choose the gRPC option.
 

Import the Proto file in Postman.


Select the ListBooks options and send a request.

 
Now, we will add a new book to the list using the CreateBook option. This gRPC service supports Create, Delete, Update, Get, and List operations. You can try it out in Postman.

Conclusion

We have successfully established a foundational gRPC service using .NET and C#. Through the implementation of a simple book management system, we have learned how to define a .proto file to structure our gRPC service and messages, and have seen how these definitions translate into server-side logic in C#.

gRPC offers significant advantages in terms of performance and flexibility when compared to traditional REST APIs, particularly in microservices architectures where efficient communication between services is crucial. Its use of HTTP/2 for transport, low overhead, and ability to generate cross-platform client and server code makes gRPC a powerful choice for modern application development.

Best ASP.NET Core 8.0.11 Hosting Recommendation

One of the most important things when choosing a good ASP.NET Core 8.0.11 hosting is the feature and reliability. HostForLIFE is the leading provider of Windows hosting and affordable ASP.NET Core, their servers are optimized for PHP web applications. The performance and the uptime of the hosting service are excellent and the features of the web hosting plan are even greater than what many hosting providers ask you to pay for. 

At HostForLIFE.eu, customers can also experience fast ASP.NET Core hosting. The company invested a lot of money to ensure the best and fastest performance of the datacenters, servers, network and other facilities. Its datacenters are equipped with the top equipments like cooling system, fire detection, high speed Internet connection, and so on. That is why HostForLIFEASP.NET guarantees 99.9% uptime for ASP.NET Core. And the engineers do regular maintenance and monitoring works to assure its Orchard hosting are security and always up.

Read More...

Tuesday, 7 January 2025

Learning the Host in ASP.NET Core

Leave a Comment

The host is a key idea in ASP.NET Core that is in charge of overseeing the dependencies and lifecycle of the application. It is the environment in which the application operates and is necessary for middleware pipelines, configuration, and service setup.

Types of Hosts in ASP.NET Core
  1. Generic Host (IHost)
    • Introduced in ASP.NET Core 3.0 to provide a unified hosting model.
    • Can host various types of applications, including web applications, background services, and more.
    • Works with non-HTTP workloads (e.g., worker services).
  2. Web Host (IWebHost)
    • Used specifically for web applications.
    • Configures HTTP servers, middleware, and other web-specific services.
    • It is now built on top of the Generic Host starting in ASP.NET Core 3.0.
Responsibilities of the Host

The host provides the following functionalities for an ASP.NET Core application.

  1. Dependency Injection (DI): It manages the application's service container and resolves services as needed.
  2. Configuration: Loads and manages configuration settings from various sources like appsettings.json, environment variables, command-line arguments, and more.
  3. Logging: Sets up logging providers (e.g., console, debug, file) for the application.
  4. Environment Management: Defines the environment the app is running in (e.g., Development, Staging, Production) using IHostEnvironment.
  5. Application Lifetime Management: Manages the application's lifecycle, including startup, shutdown, and handling graceful termination.
Components of the Host
  1. Host Builder: The HostBuilder or WebHostBuilder is used to configure and build the host.
  2. Startup Class: The Startup class defines the middleware pipeline and services configuration.
  3. Hosting Environment: Provides information about the environment, such as Development, Staging, or Production.
  4. Server: Includes the web server implementation (e.g., Kestrel, IIS) for web hosts.
Building the Host

Here’s how a host is typically built in an ASP.NET Core application.

Using Generic Host (IHost)

var builder = Host.CreateDefaultBuilder(args)
    .ConfigureServices((context, services) =>
    {
        // Add application services here
        services.AddHostedService<MyBackgroundService>();
    })
    .ConfigureLogging(logging =>
    {
        logging.ClearProviders();
        logging.AddConsole();
    });
var app = builder.Build();
await app.RunAsync();

Using Web Host (IWebHost)

var builder = WebHost.CreateDefaultBuilder(args)
    .UseStartup<Startup>()
    .UseUrls("http://localhost:5000");

var host = builder.Build();

await host.RunAsync();

Key APIs for the Host

  1. IHost
    • Represents the generic host in ASP.NET Core.
    • Example: var host = Host.CreateDefaultBuilder(args).Build();
  2. IWebHost
    • Represents the web-specific host.
    • Example: var webHost = WebHost.CreateDefaultBuilder(args).Build();
  3. IHostEnvironment
    • Provides access to environment-specific details.
    • Example: env.EnvironmentName, env.ContentRootPath.

Hosting Environment

The hosting environment determines how the application behaves in different scenarios. It is specified using the ASPNETCORE_ENVIRONMENT environment variable. Common values include.

  • Development
  • Staging
  • Production

You can access the environment in Startup.

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }
    else
    {
        app.UseExceptionHandler("/Home/Error");
    }
}

Real-World Example: Web Application Host

public class Program
{
    public static void Main(string[] args)
    {
        CreateHostBuilder(args).Build().Run();
    }
    public static IHostBuilder CreateHostBuilder(string[] args) =>
        Host.CreateDefaultBuilder(args)
            .ConfigureWebHostDefaults(webBuilder =>
            {
                webBuilder.UseStartup<Startup>();
            });
}

In this example.

  • Host.CreateDefaultBuilder(args) creates a default Generic Host.
  • ConfigureWebHostDefaults configures it for web hosting using Startup.

Best ASP.NET Core 8.0.8 Hosting Recommendation

One of the most important things when choosing a good ASP.NET Core 8.0 hosting is the feature and reliability. HostForLIFE is the leading provider of Windows hosting and affordable ASP.NET Core, their servers are optimized for PHP web applications. The performance and the uptime of the hosting service are excellent and the features of the web hosting plan are even greater than what many hosting providers ask you to pay for. 

At HostForLIFE.eu, customers can also experience fast ASP.NET Core hosting. The company invested a lot of money to ensure the best and fastest performance of the datacenters, servers, network and other facilities. Its datacenters are equipped with the top equipments like cooling system, fire detection, high speed Internet connection, and so on. That is why HostForLIFEASP.NET guarantees 99.9% uptime for ASP.NET Core. And the engineers do regular maintenance and monitoring works to assure its Orchard hosting are security and always up.

 

Read More...