Sunday, July 23, 2017

How to intercept HTTP request? asp.net core, IHTTPModule, middleware

Asp.net core is a brand new, open source and cross platform framework for building modern internet applications. Unlike its predecessor Asp.net core is lightweight, robust, fast (Kestrel Web server), and cloud ready.

Asp.net core is designed to integrate seamlessly with varieties of client side frameworks like AngularJS, ReactJS, KnockoutJS

Modern internet applications communication language is HTTP. So you will came across many scenarios to intercept client’s HTTP request and process it. I will explain a real scenario, “As part of application authentication, you have to make sure user\company employee must be logged into their corporate network/global login before accessing application.”

In Asp.net core Middleware’s replaced IHTTPModule and IHTTPHandler.  Middleware is an application pipeline to handle request and response .

I will quickly walk through you the code snippets:
         First create two class as below
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace WebApplication5.Middleware
{
    public class CustomMiddleware
    {
        private readonly RequestDelegate _next;

        public CustomMiddleware(RequestDelegate next)
        {
            _next = next;
        }

        public async Task Invoke(HttpContext context)
        {
         
            string companyAuthCookie = ApiHelper.GetConfigValue("companyAuthCookie");
            bool securityEnabled = bool.Parse(ApiHelper.GetConfigValue("SecurityEnabled"));

            if (securityEnabled)
            {
                var header = context.Request.Headers;
                var cookies = context.Request.Cookies;

                if (cookies.ContainsKey(companyAuthCookie))
                {
                    //allow other middle to process http request
                    await _next.Invoke(context);
                }
                else
                {
                    //short circuit or terminate http process request because user haven't logged in
                    context.Response.Redirect(ApiHelper.GetConfigValue("RedirectUrl"));
                }
            }
            else
            {
                await _next.Invoke(context);
            }
        }
    }

    public static class CustomMiddlewareExtensions
    {
        public static IApplicationBuilder UseCSPMiddleware(this IApplicationBuilder builder)
        {
            return builder.UseMiddleware<CustomMiddleware>();
        }
    }
}

Then goto Startup class (Startup.cs)

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
        {
            loggerFactory.AddConsole(Configuration.GetSection("Logging"));
            loggerFactory.AddDebug();

               //in asp.net core order is important. Make sure you call it in early stage
            app.UseCSPMiddleware();

            app.UseMvc();
        }

That’s it, you have created code to intercept http request and process it inside asp.net core.

Reference: 

Friday, July 7, 2017

Quotes by Mahesh

"Give me Data, I will give you the past or future" mcsj

"Gratitude is very rare, not Diamonds." mcsj

"Human life is a  precious gift,  ask plants, birds and animals" mcsj

"Once you understand a System thoroughly, then you can take control of it" mcsj

"Its very difficult to impress Aries" mcsj

"Where there is Quality, There is Demand" mcsj

"Where there is Healthy Competition, there is Creativity/Invention/Innovation" mcsj

"Best investment for a Nation, Family, Individual is on Education" mcsj

"Where there is no principles, structure, and order, there is no growth." mcsj

"A star gets birth, only to shine bright, remember you are a STAR " mcsj

"Your behavior decides, your education and social background" mcsj

"To understand a system, you have two choice, start all over, spend 100/1000 years on finding patterns or read books" mcsj

"Inside Mathematics, at any point of time you will be either doing JUST addition or subtraction" mcsj

"To solve issues or enhance or improve a system, first you have to understand the System" mcsj

"What is more important is whether you LIKE it or not, you should never worry about the price or anything else, life is short" mcsj

"What matter's is what do you do, not where you are" mcsj

"The only way to pierce into the minds of genius is by reading their book" mcsj

"Benefits of travel, it will make you wise, entrepreneur, humble,  knowledge... " mcsj

"There are two kinds of people in the world, one who writes book, another who reads it" mcsj

"Queen must wait till she finds a guy with character\behavior of  a King" mcsj

"One of the toughest task is, to communicate/exchange ideas/thoughts with people, without hurting their feelings" mcsj

"If you think its there, it is there, if no, it is not there, everything boils down to what you think" mcsj

"Greatest tips/tricks for any startup or work is, 'you just start working on it' " mcsj

"For  certain category/group of kids, teach them basics, they will teach you advanced" mcsj

"The only way to travel fastest in the past is by reading a book" mcsj


"In theory with energy (e=mc2) we can travel, back into past or future, but with data  practically we   can go back into past or future" mcsj

"Excellent communicator or people manager is one who knows that, every individuals activity\personality\character is determined by the data inside their Brain" mcsj

To those who care
for people and mankind