Implementing Swagger in Asp.net Web API Core 3.1 in clean way


What is the Swagger ?

This is one of the best tool for testing web api method. It will also give very good user friendly definition of web api method.

Advantages:
1. We can easily test web api method
2. We will get user friendly documented message about web api method
3. We can easily debug the web api method using this tool.

How to implement in Asp.net Web API Core 3.1 in Clean way ?

Step 1: Firstly create the web api 3.1 project like this

Creating Web Api Core 3.0 layer using Dapper and .net standard 2.0

Step 2: Go to Web API layer and install the swagger related nuget package

Swagger
Swagger

Note: if you are using asp.net core 3.0 or 3.1 then install the swagger version v5.0

Step 3: Create SwaggerExtension.cs file in the Extensions folder of We API Layer and write the Extension Method for IServiceCollection and IApplicationBuilder like this

using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.OpenApi.Models;

namespace Dapper_Demo.Extensions
{
    public static class SwaggerExtension
    {
        public static void AddSwagger(this IServiceCollection services)
        {
            // Register the Swagger generator, defining 1 or more Swagger documents
            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new OpenApiInfo { Title = "EmpManagement API", Version = "v1" });
            });
        }

        public static void AddCustomSwagger(this IApplicationBuilder app)
        {
            //Adding Swagger and SwaggerUI
            app.UseSwagger();

            app.UseSwaggerUI(c =>
            {
                c.SwaggerEndpoint("/swagger/v1/swagger.json", "EmpManagement ASP.NET Core API v1");
            });
        }
    }
}

Step 4: Go to the Startup file of application and add the swagger in middleware and service configure like this

Swagger_Middleware
Swagger_Middleware

Step 5: Run the application and type this URL

If you want to download the source code for this demo. You can download from below demo.

https://github.com/Chandradev819/Dapper_Demo_With_Asp.netCore

Advertisement

How to enable cross domain Ajax call in asp.net Web API 2.0 ? (Part 10)


If we have created the Web API service and we are going to consume the service in same application then we will not get any exception. But the same service if we are going to call the other application, we will get the exception

No ‘Access-Control-Allow-Origin’ header is present on the requested resource

To fix this issue we have to make the cross domain enable ajax call in our service

It is very simple to implement this functionality

Step 1: Install the Microsoft.AspNet.WebApi.Cors plugin from Nuget package manager

Step 2: Go to WebApiConfig file and the code like this

Step 3: Now you can write the ajax call to consume the service as similar as previous post

How to consume web api using Jquery

How to consume the web api basic authentication method using JQuery ? (Part 9)


In the previous post Part 8, we show that how to test the basic authentication web api using postman.
But if we have to consume the basic authentication web api method in Jquery, then we have to add headers attribute in ajax call.

Complete sample code as given below.

@{
    ViewBag.Title = "Index";
}

<script src="~/Scripts/jquery-1.10.2.js"></script>

<script type="text/javascript">
    
    function drawTable(data) {
        for (var i = 0; i < data.length; i++) {
            drawRow(data[i]);
        }
    }
    function drawRow(rowData) {
        var row = $("<tr />")
        $("#EmpDataTable").append(row);
        row.append($("<td>" + rowData.Id + "</td>"));
        row.append($("<td>" + rowData.EmpName + "</td>"));
        row.append($("<td>" + rowData.EmpAddress + "</td>"));
    }
    
    $(document).ready(function () {
        $("#btnget").on('click', function (e) {
            var username = "Admin";
            var password = "Admin";
            e.preventDefault();
            $.ajax({
                url: "http://localhost:64410/api/Emps_API_/2",
                type: "GET",
                cache: false,
                contentType: "application/json",
                dataType: "json",
                headers: { 'Authorization': 'Basic ' + btoa(username + ':' + password) }
            }).done(function (data) {
                $('#tbdata tbody').empty();
                if (!jQuery.isArray(data)) data = [data];
                drawTable(data);
                $('#btnget').prop('disabled', true);
            }).error(function (xhr, textStatus, errorThrown) {
                alert("Err " + textStatus + "   " + errorThrown);
            });
           
        });
    });
</script>

<h2>Index</h2>
<table class="table table-bordered table-striped">
    <tr>
        <td>Click Here to Received the Employee</td>
        <td>
            <input type="button" id="btnget" value="Get" />
        </td>
    </tr>

</table>

<table class="table-bordered table-striped table table-hover" id="EmpDataTable">
    <tr>
        <th>Id</th>
        <th>Emp Name</th>
        <th>EmpAddress</th>
    </tr>

</table>

Note : in the above code headers attributes of Jquery to pass the ‘Authorization’: ‘Basic ‘ + btoa(username + ‘:’ + password), which is required to do the basic authentication process.

Here btoa is JavaScript method to convert the string to base-64 code.

How to Implement Basic Authentication in Asp.net Web API 2.0 ? (Part 8)


As the name suggest, it is the most simple and basic process of doing authentication of HTTP Request in asp.net Web API.
In this process client sends the Base64-encoded credentials to the authorize header on every HTTP request, and after verification process Web API return the expected HTTP Response

In this process, it doesn’t use Session or cookies.

Step 1: Create the BasicAuthenticationAttribute class and write code for doing validation like given below


using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Web;
using System.Web.Http.Filters;

namespace WebApi_Sample.Security
{
    public class BasicAuthenticationAttribute: AuthorizationFilterAttribute
    {
        public override void OnAuthorization(System.Web.Http.Controllers.HttpActionContext actionContext)
        {
            if (actionContext.Request.Headers.Authorization == null)
            {
                actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.Unauthorized);
            }
            else
            {
                // Gets header parameters  
                string authenticationString = actionContext.Request.Headers.Authorization.Parameter;
                string originalString = Encoding.UTF8.GetString(Convert.FromBase64String(authenticationString));

                // Gets username and password  
                string usrename = originalString.Split(':')[0];
                string password = originalString.Split(':')[1];

                // Validate username and password  
                if (!ValidateUser.VaidateUser(usrename, password))
                {
                    // returns unauthorized error  
                    actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.Unauthorized);
                }
            }

            base.OnAuthorization(actionContext);
        }

    }
}

Step 2: Create the ValidateUser Class and write the code for doing validation in database on basis of UserName and password

namespace WebApi_Sample.Security
{
    public class ValidateUser
    {
        public static bool VaidateUser(string username, string password)
        {
            // Check if it is valid credential  
            // Here we have just hardcoded the value 
            if (username.Equals("Admin") && password.Equals("Admin")) 
            {
                return true;
            }
            else
            {
                return false;
            }
        }
    }
}

Step 3: Use the basic BasicAuthentication Attribute on the Controller as given below

Step 4. Now lunch the Postman tool and select the basic authentication option and pass the username and password as given below image

You will the get the excepted data as output.

How to secure the Asp.net Web API 2.0 ? (Part 7)


There are so many ways to secure the Web API. But in this post we will see the Authentication process using “Message Handler”.

As we know in asp.net Web API, before execution of any controller, Httprequest go through the message Handler pipeline sequence as given below image

So if we have to implement the some custom validation logic, it will be better to write code in Message Handler.

What is the Message Handler in asp.net Web API ?

>> A message handler is a class that receives an HTTP request and returns an HTTP response. Message handlers derive from the abstract HttpMessageHandler class.

There will be series of message handlers are chained together. The first handler receives an HTTP request, does some processing, and gives the request to the next handler. At some point, the response is created and goes back up the chain as shown in above image. This pattern is also called a delegating handler.

How to write the Custom Message Handler ?
So many time we will get the scenario to write our own logic in Message Handler to perform some specific task on that scenario we have to create Custom Message handler.

To write the Custom Message Handler we have to

1. Inherit the System.Net.Http.DelegatingHandler
2. Override SendAsync Method of HttpMessageHandler as given below

 protected async override Task<HttpResponseMessage> SendAsync(
        HttpRequestMessage request, CancellationToken cancellationToken)
   {
      // Here will be our own login
  }

How to implement Custom Authentication process in Message Handler ?

>> From client side we can pass the some Key and Value as Authentication Token. As we know before execution of API controller it will go through the message handler pipeline so in Message handler we have to validate the given Token Value, if it is correct then further execution will happen else we will send the Forbidden request

Step 1: Create some class like APIKeyHandler in Some folder like Security

Step 2: Write the logic as given below in APIKeyHandler class

using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;

namespace WebApi_Sample.Security
{
    public class APIKeyHandler : DelegatingHandler
    {
        //set a default API key 
        private const string yourApiValue = "API_Sample_Value";
        

        protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
        {
            bool isValidAPIKey = false;
            IEnumerable<string> lsHeaders;
            //Validate that the api key exists

            var checkApiKeyExists = request.Headers.TryGetValues("Sample_Key", out lsHeaders);

            if (checkApiKeyExists)
            {
                if (lsHeaders.FirstOrDefault().Equals(yourApiValue))
                {
                    isValidAPIKey = true;
                }
            }

            //If the key is not valid, return an http status code.
            if (!isValidAPIKey)
                return request.CreateResponse(HttpStatusCode.Forbidden, "Sorry you have provide wrong API key.");

            //Allow the request to process further down the pipeline
            var response = await base.SendAsync(request, cancellationToken);

            //Return the response back up the chain
            return response;
        }
    }
} 

Note: In the above code DelegatingHandler is abstract class which has overridden the method of HttpMessageHandler Class.
In the above code we are passing the yourApiValue= “API_Sample_Value” and Key =”Sample_Key”

If the given input from client side is correct then it will Allow the request to process further down the pipeline else it will terminate the request.

Step 3: Register the Custom Message Code in the Application_Startmethod of Global.asax file like this

GlobalConfiguration.Configuration.MessageHandlers.Add(new APIKeyHandler());

Step 4: Run the application and Test the Api Controller get method from PostMan Tool