.Net 6 : Jwt Authentication in Minimal Web Api

In the previous post, we delved into Jwt Authentication implementation in the .Net Core 5. In this post, we will create a Minimal Web API (introduced in .Net 6) and implement Jwt Authentication in it.

Minimal Web API allows developers to build low ceremony web apis without the overhead of ceremonial code in traditional Asp.Net core MVC solution. The traditional Web API core adds so much ceremonial code to your application that it could confuse the beginners.Starting with .Net 6 Preview 4, you can build minimal API’s which are devoid of any ceremonial code – write only what you want !!

You can create a minimal Web Api solution using the following command

dotnet new web

This would provide you the basic skeleton for the project. The code is build on the Top Level Programs feature introduced in C# 9, which allows you to declare and execute programs without the need for writing ceremonial code like class and namespace or main.

So let us write our minimal Web Api for implementing Jwt Authentication now.

var builder = WebApplication.CreateBuilder(args);
await using var app = builder.Build();

if (app.Environment.IsDevelopment())
{
    app.UseDeveloperExceptionPage();
}

app.MapGet("/", (Func<string>)(() => "This a demo for JWT Authentication using Minimalist Web API"));
await app.RunAsync();

A minimal code Web Api could look like the above. Isn’t that clean ?

Dependency Injection

To add authentication, we would add couple of services which would help us on the way. First we will add a ITokenService which would provide us the token. We will also add IUserRepositoryService which would allow us to mock the users for sake of example (let us not complicate things with a Db here).

But first we need to add a nuget package which would allow us to use Dependency injection – Microsoft.Extensions.DependencyInjection.

At this point, we will make use of another .Net 6 feature – Global using. This would allow us to move all our using statements to a single location and allow further clean up code. Read on Global using here.

Add a new file called “Usings.cs” and move all your using statements.

global using System;
global using System.ComponentModel.DataAnnotations;
global using Microsoft.AspNetCore.Builder;
global using Microsoft.AspNetCore.Http;
global using Microsoft.Extensions.Hosting;
global using System.Collections.Generic;
global using System.Linq;
global using Microsoft.Extensions.DependencyInjection;
global using System.Security.Claims;
global using System.Text;
global using Microsoft.IdentityModel.Tokens;
global using System.IdentityModel.Tokens.Jwt;
global using Microsoft.AspNetCore.Authentication.JwtBearer;
global using Microsoft.AspNetCore.Authorization;

Alright back to the task in our hand. With the package of Dependency Injection added, we can now register our services.

builder.Services.AddSingleton<ITokenService>(new TokenService());
builder.Services.AddSingleton<IUserRepositoryService>(new UserRepositoryService());

For sake of example, we will use the same implementation of TokenService and UserRepositoryService as we had used in the earlier post on Jwt authentication.



public interface IUserRepositoryService
{
    UserDto GetUser(UserModel userModel);
}
public class UserRepositoryService : IUserRepositoryService
{
    private List<UserDto> _users => new ()
    {
        new ("Anu Viswan","anu"),
        new ("Jia Anu","jia"),
        new ("Naina Anu","naina"),
        new ("Sreena Anu","sreena"),
    };
    public UserDto GetUser(UserModel userModel)
    {
        return _users.FirstOrDefault(x => string.Equals(x.UserName,userModel.UserName) && string.Equals(x.Password, userModel.Password));
    }
}

public interface ITokenService
{
    string BuildToken(string key, string issuer, UserDto user);
}
public class TokenService : ITokenService
{
    private TimeSpan ExpiryDuration = new TimeSpan(0, 30, 0);
    public string BuildToken(string key, string issuer, UserDto user)
    {
        var claims = new[]
        {
                new Claim(ClaimTypes.Name, user.UserName),
                new Claim(ClaimTypes.NameIdentifier,
                Guid.NewGuid().ToString())
             };

        var securityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(key));
        var credentials = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256Signature);
        var tokenDescriptor = new JwtSecurityToken(issuer, issuer, claims,
            expires: DateTime.Now.Add(ExpiryDuration), signingCredentials: credentials);
        return new JwtSecurityTokenHandler().WriteToken(tokenDescriptor);
    }
}

We will also use two POCO’s which would help us transfer data.

public record UserDto(string UserName,string Password);

public record UserModel
{
    [Required]
    public string UserName { get; set; }

    [Required]
    public string Password { get; set; }
}

Note that we are using another .Net 5 feature here – record.

Add Middleware

The next step would be to configure and add the middleware for supporting Authentication and Authorization.

builder.Services.AddAuthorization();
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).AddJwtBearer(opt =>
{
    opt.TokenValidationParameters = new ()
    {
        ValidateIssuer = true,
        ValidateAudience = true,
        ValidateLifetime = true,
        ValidateIssuerSigningKey = true,
        ValidIssuer = builder.Configuration["Jwt:Issuer"],
        ValidAudience = builder.Configuration["Jwt:Issuer"],
        IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(builder.Configuration["Jwt:Key"]))
    };
});

We will use the WebApplicationBuilder instance to configure our middleware and use the the WebApplication instance to plugin our middleware.

app.UseAuthentication();
app.UseAuthorization();

Actions

Now we are all set to write our Login and Protected Action. We will first write our Login Action.

app.MapGet("/login", [AllowAnonymous] async (HttpContext http,ITokenService tokenService,IUserRepositoryService userRepositoryService) => {
    var userModel = await http.Request.ReadFromJsonAsync<UserModel>();
    var userDto = userRepositoryService.GetUser(userModel);
    if (userDto == null)
    {
        http.Response.StatusCode = 401;
        return;
    }

    var token = tokenService.BuildToken(builder.Configuration["Jwt:Key"], builder.Configuration["Jwt:Issuer"], userDto);
    await http.Response.WriteAsJsonAsync(new { token = token });
    return;
});

Notice we have also made use of Dependency Injection to use our services, which had registered in the previous steps. We then use the UserRepositoryService and TokenService to validate and generate token for our User.

Another important point to note here is how we used the [AllowAnonymous] attribute inline.

The protected action doesn’t do much. We have kept it as simple as possible for sake of the example.

app.MapGet("/doaction", (Func<string>)([Authorize]() => "Action Succeeded"));

That’s all you need to do to implement Jwt Authentication using Minimal API. The whole implementation looks like the following.


var builder = WebApplication.CreateBuilder(args);
builder.Services.AddSingleton<ITokenService>(new TokenService());
builder.Services.AddSingleton<IUserRepositoryService>(new UserRepositoryService());
builder.Services.AddAuthorization();
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).AddJwtBearer(opt =>
{
    opt.TokenValidationParameters = new ()
    {
        ValidateIssuer = true,
        ValidateAudience = true,
        ValidateLifetime = true,
        ValidateIssuerSigningKey = true,
        ValidIssuer = builder.Configuration["Jwt:Issuer"],
        ValidAudience = builder.Configuration["Jwt:Issuer"],
        IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(builder.Configuration["Jwt:Key"]))
    };
});

await using var app = builder.Build();
app.UseAuthentication();
app.UseAuthorization();

if (app.Environment.IsDevelopment())
{
    app.UseDeveloperExceptionPage();
}

app.MapGet("/", (Func<string>)(() => "This a demo for JWT Authentication using Minimalist Web API"));

app.MapGet("/login", [AllowAnonymous] async (HttpContext http,ITokenService tokenService,IUserRepositoryService userRepositoryService) => {
    var userModel = await http.Request.ReadFromJsonAsync<UserModel>();
    var userDto = userRepositoryService.GetUser(userModel);
    if (userDto == null)
    {
        http.Response.StatusCode = 401;
        return;
    }

    var token = tokenService.BuildToken(builder.Configuration["Jwt:Key"], builder.Configuration["Jwt:Issuer"], userDto);
    await http.Response.WriteAsJsonAsync(new { token = token });
    return;
});

app.MapGet("/doaction", (Func<string>)([Authorize]() => "Action Succeeded"));

await app.RunAsync();

public record UserDto(string UserName,string Password);

public record UserModel
{
    [Required]
    public string UserName { get; set; }

    [Required]
    public string Password { get; set; }
}

public interface IUserRepositoryService
{
    UserDto GetUser(UserModel userModel);
}
public class UserRepositoryService : IUserRepositoryService
{
    private List<UserDto> _users => new ()
    {
        new ("Anu Viswan","anu"),
        new ("Jia Anu","jia"),
        new ("Naina Anu","naina"),
        new ("Sreena Anu","sreena"),
    };
    public UserDto GetUser(UserModel userModel)
    {
        return _users.FirstOrDefault(x => string.Equals(x.UserName,userModel.UserName) && string.Equals(x.Password, userModel.Password));
    }
}

public interface ITokenService
{
    string BuildToken(string key, string issuer, UserDto user);
}
public class TokenService : ITokenService
{
    private TimeSpan ExpiryDuration = new TimeSpan(0, 30, 0);
    public string BuildToken(string key, string issuer, UserDto user)
    {
        var claims = new[]
        {
                new Claim(ClaimTypes.Name, user.UserName),
                new Claim(ClaimTypes.NameIdentifier,
                Guid.NewGuid().ToString())
             };

        var securityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(key));
        var credentials = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256Signature);
        var tokenDescriptor = new JwtSecurityToken(issuer, issuer, claims,
            expires: DateTime.Now.Add(ExpiryDuration), signingCredentials: credentials);
        return new JwtSecurityTokenHandler().WriteToken(tokenDescriptor);
    }
}


You can find the code given in the example in my Github.

That’s all for now, Happy weekend !!

Jwt Authentication using .Net Core 5

In this blog post we will look into JWT Authentication and its implementation using .Net Core Web Api. We will try to keep things as simple as possible, while taking time to explain the key concepts in best possible way. For same reason, we will mock our User repository with static entries.

Json Web Token

Json Web Token or JWT is an open standard for securely transmitting self contained messages between parties as Json Objects. These messages are verifiable as they are digitally signed. They are extremely compact compared to Simple Web Tokens (SWT) and could be used for Authentication as well as information exchange.

  • Authentication – After the initial sign in, each request send by client would contain JWT token, which would be read and used by the Server for authorization.
  • Information Exchange – Multiple parties could exchange secure information as they digitally signed. The signature component of the JWT(we will get it shortly) contains the hash of header and payload ensuring the message is not tampered with.

Structure of JWT

The key structure of JWT contains three parts in the following format.

Header.Payload.Signature

Let us examine each part.

Header – The Header contains information on the type of token and the hashing algorithm used. Typical header might look like

{
    'alg':'H256',
    'typ':'Jwt'
}

Payload – Payload contains claims, which are information about the entity and any additional information required. Claims are broadly categorized into 3 types.

  • Registered Claims – A set of predefined non-mandatory claims which can used to provide useful information.
  • Public Claims – Custom claims which are defined and registered with IANA (Internet Assigned Numbers Authoriry) Json web Token registry.
  • Private Claims – Custom claims which are defined and used by parties, but are neither predefined or registered.

Typical Payload might look like

{
    "iss":"www.hello.com",
    "sub":"123456",
    "name":"John Doe",
    "admin":true
}

Signature – The third and final part of JWT token structure is known as Signature. This comprises of Base64 encoded Header and Payload, which is then applied with the algorithm specified in the header with a secret key. The signed part ensure that the message wasn’t tampered with. Typical signature might look like

HMACSHA256( base64(header) + "." +   base64(payload), secret)

How does JWT Token work.

JWT authentication works in a simple way.

  • During the authentication process, the user inputs (username/password) are validated by the server and a token is generated. This token is then send back to the caller.
  • Caller stores the token internally and for each susequent request for a protected resource, it would include the token in the Authorization Header using the Bearer Schema.
  • The server would validate the further requests based on the token recieved. It would allow the request to access the protected source if the token is successfully validate.

Implementation of JWT Token in .Net Core 5 Web Api.

Alright, enough of talkng about JWT. Let us now start writing some code.

The first step would be to store our secret key and algorithm for signature in the AppSettings.Json, along with any additional information required. This might typically look like

"Jwt": {
    "Key": "ThisWouldBeReplacedBySecretKey",
    "Issuer": "www.bytelanguage.net",
    "Audience": "http://www.hello.com"
  }

We will now proceed to configure the authentication service and schema. The authentication is done using the IAuthenticationService which provides the ClaimPrincipal instance for the authorization to take decisions against. Schema refers to the authentication handlers and options for configuring each handler.

The Authentication Handlers create the Authentication ticket which represents the User Identity. Additionally it returns no result/failure when the Authentication fails. It also executes the challenge or forbid actions when an protected resource is accessed.

We configure the service and schema using the ConfigureService method.

 services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).AddJwtBearer(opt =>
{
    opt.TokenValidationParameters = new Microsoft.IdentityModel.Tokens.TokenValidationParameters
    {
        ValidateIssuer = true,
        ValidateAudience = true,
        ValidateLifetime = true,
        ValidateIssuerSigningKey = true,
        ValidIssuer = Configuration["Jwt:Issuer"],
        ValidAudience = Configuration["Jwt:Issuer"],
        IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["Jwt:Key"]))
    };
});

In the above code, we have added registered the service required for authentication along with the Schema. AddAuthentication method registers the service used for authentication and returns a AuthenticationBuilder instance which can be further used for configuring the authentication. We have also specified that the JwtBearer would be responsible for authenticating the credentials using the token extracted from the Authorization Header, using the AddJwtBearer extension method.

.Net Core uses middlewares for handling Authentication and authorizations. The next step involves ensuring the Authentication and Authorization middlewares are plugged in our execution pipeline. This is done using the Configure() method.

app.UseAuthentication();
app.UseAuthorization();

A word of caution here. Since the middlewares are typically executed in the order they are registered, you need to ensure that the Authentication/Authorization middleware are in their right place. Usually you would want them after the routing middleware, and before the end points middleware.

Now that we have defined and registered our middlewares, it is time to define couple of services.

  • TokenService : which would be responsible for generating the token.
  • UserRepositoryService : Which would mock the user repository for us (Remember, as mentioned in the earlier part of article, we are not using any actual db in this example)

TokenService

The Token Service comprises of a single method.

public interface ITokenService
{
    string BuildToken(string key, string issuer, UserDto user);
}

The method would accept a secret key, an issuer and the UserDto, and would return a string representing the Jwt Token.

Let us go ahead and implement the service now.

public class TokenService : ITokenService
{
    private TimeSpan ExpiryDuration = new TimeSpan(0, 30,0);
    public string BuildToken(string key, string issuer, UserDto user)
    {
        var claims = new[]
        {
            new Claim(ClaimTypes.Name, user.UserName),
            new Claim(ClaimTypes.Role, user.Role),
            new Claim(ClaimTypes.NameIdentifier,
            Guid.NewGuid().ToString())
            };

        var securityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(key));
        var credentials = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256Signature);
        var tokenDescriptor = new JwtSecurityToken(issuer, issuer, claims,
            expires: DateTime.Now.Add(ExpiryDuration), signingCredentials: credentials);
        return new JwtSecurityTokenHandler().WriteToken(tokenDescriptor);
    }
}

In the above code, we have created a set of Claims representing the User identity. We have also set a expiry for the token and then used the HmacSha256 algorithm to sign the token.

Repository Service

As mentioned earlier, this would be a simple class which would mock the User repository for us (as we do not want to complicate the example in hand with use of Db). For same reason, we will keep it as simple as possible.

public interface IUserRepositoryService
{
    UserDto GetUser(UserModel userModel);
}

public class UserRepositoryService:IUserRepositoryService
{
    private List<UserDto> _userCollection = new List<UserDto>();
    public UserRepositoryService()
    {
        _userCollection.AddRange(new[]
        {
            new UserDto("Anu Viswan","anu","admin"),
            new UserDto("Jia Anu","jia","admin"),
            new UserDto("Naina Anu","naina","admin"),
            new UserDto("Sreena Anu","sree","admin"),
        });
    }

    public UserDto GetUser(UserModel userModel)
    {
        return _userCollection.Single(x=>string.Equals(x.UserName,userModel.UserName) && string.Equals(x.Password,userModel.Password));
    }
}

The service exposes a method called GetUserModel which would accept a POCO and return the a User Dto representing User with same user name (and password – effectively validating)mentioned in the POCO. The UserModel and UserDto are defined as

public record UserModel
{
    [Required]
    public string UserName { get; set; }

    [Required]
    public string Password { get; set; }
}

public record UserDto(string UserName,string Password,string Role)
{
}

Withour services in place, it is time to ensure we have ability to inject them into our controllers. We do this by adding into our ServiceCollection using the ConfigureServices() method.

services.AddTransient<ITokenService, TokenService>();
services.AddTransient<IUserRepositoryService, UserRepositoryService>();

We can now inject them our constructor.

private readonly ITokenService _tokenService;
private readonly IUserRepositoryService _userRepositoryService;
private readonly IConfiguration _configuration;
public HomeController(ITokenService tokenService,IUserRepositoryService userRepositoryService,IConfiguration config )
{
    _tokenService = tokenService;
    _userRepositoryService = userRepositoryService;
    _configuration = config;
}

Login Action

Now we have almost everything that we require for authentication and generation of token. We have registered and configured our middlewares, and so have created service for token generation. Let us now write the Login action which would used by the clients for logging into the system.

[AllowAnonymous]
[Route("login")]
[HttpPost]
public ActionResult Login(UserModel userModel)
{
    if(string.IsNullOrEmpty(userModel.UserName) || string.IsNullOrEmpty(userModel.Password))
    {
        return RedirectToAction("Error");
    }

    IActionResult response = Unauthorized();
    var user = _userRepositoryService.GetUser(userModel);

    if(user != null)
    {
        var generatedToken = _tokenService.BuildToken(_configuration["Jwt:Key"].ToString(), _configuration["Jwt:Issuer"].ToString(), user);
        return Ok(new
        {
            token = generatedToken,
            user = user.UserName
        });

    }
    return RedirectToAction("Error");
}

private UserDto GetUser(UserModel userModel)
{
    return new UserDto("Jia", "admin", "admin");

}

Notice that we have applied the [AllowAnonymous] attribute to the action. This instructs that the action is an unprotected resource and could be accessed by an non-authenticated user. This is of course required, otherwise the user will never be able authenticate himself.

As seen in the code above, we retrieve the UserRepository Service to retrieve the User Dto using the data we received from the client. The validated user would then generated a token using the ITokenService.

var generatedToken = _tokenService.BuildToken(_configuration["Jwt:Key"].ToString(), _configuration["Jwt:Issuer"].ToString(), user);

At this point, we are also retrieving the configuration information we had stored in the AppSettings.Json in the first step, including the secret key. The Generated token is then send back to the caller.

Authorizing the Protected resources

We decorate the protected resources using the [Authorize] attribute to specify that they need authentication. For example,

[Authorize]
[Route("Secret")]
[HttpPost]
public ActionResult SecretFunction()
{
    return Ok("Alright, you are authorized user");
}

The Action Secret can be now accessed only by an authenticated user. The authentication handlers would execute a Challenge/Forbid action every time an unauthorized user attempts to access a protected resource.

That was a brief walk through for implementing Jwt authentication using .Net Core 5. The code in the post could can be found in my github here. The complete process can be summarized as the following.

JWT Authentication

API based Custom FormValidation using SemanticUI/Jquery

In the last post, we discussed on how to implement form validation and subsequent submit using the Semantic UI and JQuery. In this follow up post, we discuss how we can enhance the validation capabilities further, by having a custom validation that depends on an external API call.

For the sake of example, let’s focus on an mock User Sign Up page, where we would be checking if the username exists prior to form submit.

Let’s write down our basic form first.

<form class="ui form" method='post' id="RegisterUser">
  <h4 class="ui dividing header">User Sign Up</h4>
  <div class="field">
    <div class="two fields">
      <div class="eight wide field">
        <label>UserName</label>
        <input type="text" placeholder="Username" id="username">
      </div>
    </div>
  </div>
  <button class="ui button" tabindex="0">Sign Up</button>
  <div class="ui hidden negative message" id="formresult"></div>
  <div class="ui error message" id="formvalidation"></div>
</form>

Now, let’s create our Validation Script.

var formvalidationrules = {
    on: 'submit',
    fields: {
      username: {
        identifier: 'username',
        rules: [{
          type: 'custom',
          prompt: 'username already exists'
        }]
      },
    },
    onSuccess: function(event) {
      event.preventDefault();
    }
  };

  $('#RegisterUser').form(formvalidationrules);

As you can see, the rule type has been specified as ‘custom’. The next obvious task is to write down the method to do the custom validation itself.

$.fn.form.settings.rules.custom = function() {
    var result;
    $.ajax({
      type: 'POST',
      url: '/echo/html/',
      async: false,
      data: {
        'html': $('#username').val()
      },
      success: function(data) {
        result = !(data == 'test');

      },
    });
    return result;

  };

Couple of things to note here.
a) The rule method has been added to form.settings.rules.
b) Now this is very important, your ajax calls needs to be synchronous.

That’s it, you are ready to roll. Check out the script in action in Fiddle Link

Form Validation and Submit using Semantic UI and JQuery

Bootstrap, despite all the effort to make it easily understandable, always relied heavily on its short hand notations for css classes. This seemed okay, until Semantic UI entered the race with its near perfect usage of natural language. The fact that it is well integrated with jQuery makes it a good choice for web developers.

One of the most common tasks in any web development has to do with form. The following code illustrates how to validate the form and submit it using the Semantic UI APIs.

 

                <form class="ui large form" method="POST" role="form" id="ValidateUser">
                    <section class="ui stacked segment">
                        <div class="field">
                            <div class="ui left icon input">
                                <i class="user icon"></i>
                                @Html.TextBoxFor(a => a.UserName, new { placeholder = "UserName",id="username" })
                                @Html.ValidationMessageFor(a => a.UserName)
                            </div>
                        </div>
                        <div class="field">
                            <div class="ui left icon input">
                                <i class="lock icon"></i>
                                @Html.PasswordFor(a => a.Password, new { placeholder = "Password",id="password" })
                                @Html.ValidationMessageFor(a => a.Password)
                            </div>
                        </div>

                        <input id="submitbutton" class="ui submit fluid large green button" type="submit" value="Login"/> 
                        <!-- <div class="ui blue submit button">Submit</div> -->
                        <div class="ui hidden negative message" id="formresult"></div>
                        <div class="ui error message" id="formvalidation"></div>
                    </section>
                </form>
$(document).ready(function () {

            var urllink = '@Url.Action("Login", "Validation")';


            $('#ValidateUser').form(
                                     {
                                         on: 'blur',
                                         fields: {
                                             username: {
                                                 identifier: 'username',
                                                 rules: [{
                                                     type: 'empty',
                                                     prompt: 'Username cannot be empty'
                                                 }]
                                             },
                                             password: {
                                                 identifier: 'password',
                                                 rules: [{
                                                     type: 'empty',
                                                     prompt: 'Password cannot be emtpy'
                                                 }]
                                             }
                                         },
                                         onSuccess: function (event) {
                                             $('#formresult').hide();
                                             $('#formresult').text('');
                                             event.preventDefault();
                                             return false;
                                         }

                                     }
                                   )
                                 .api({
                                     url: urllink,
                                     method:'POST',
                                     serializeForm: true,
                                     data: new FormData(this),
                                     onSuccess: function (result) {
                                        $('#formresult').show();
                                        if (result.Success) {
                                            window.location = "/Dashboard/Dashboard";
                                        }
                                        else {

                                            $('#formresult').append(result.Msg);
                                        }
                                        return false;
                                    }
                    });


        });

Fix CORS in Firefox

CORS is a hated word anyone working on Web Solutions might have encountered if your website is accessing another website or API. So how do you ensure your website is able to the required URL ?

The first and easiest fix would be to include “Access Control” headers in your web.config.

<httpProtocol>
 <customHeaders>
 <add name="Access-Control-Allow-Origin" value="*" />
 </customHeaders>
 </httpProtocol>

That should be it for every other browser except for Firefox, particularly if you are accessing a Restful Web API. By default, Firefox assumes the Request to have “Accept” Header as “application/xml“. This can be demonstrated once your fire up your Web API in Firefox Extension RestClient.

The workaround for the problem lies in changing the “Accept” header to “application/json”.

Exception Handling in Web API (Part 2): Exception Filter (Extended)

The Exception Filter implementation mentioned in the Part1 of the article is fairly simple and straightforward.  But as you start supporting more and more Exceptions, the Cyclomatic Complexity of the “OnException” method would increase because of the “if” condition nature.

A cleaner implementation of the Filter is shown below using Dictionary.

 public class DemoExceptionFilter : ExceptionFilterAttribute
 {
 public DemoExceptionFilter()
 {
 this.ExceptionDictionary = new Dictionary();
 this.ExceptionDictionary.Add(typeof(NotImplementedException), HttpStatusCode.ServiceUnavailable);
 this.ExceptionDictionary.Add(typeof(ArgumentOutOfRangeException), HttpStatusCode.BadRequest);
 }
 public IDictionary ExceptionDictionary
 {
 get;
 private set;
 }
 public override void OnException(HttpActionExecutedContext ExecutedContext)
 {

 if (ExceptionDictionary.ContainsKey(ExecutedContext.GetType()))
 {
 ExecutedContext.Response = new HttpResponseMessage(ExceptionDictionary[ExecutedContext.GetType()]);
 
 }
 else
 {
 throw new HttpResponseException( new HttpResponseMessage(HttpStatusCode.InternalServerError));
 }
 base.OnException(ExecutedContext);
 }

 }

Isn’t that cleaner ?
 

Exception Handling in Web API (Part 1): Exception Filter

The Web World, especially Web Services is fast moving towards the more abstract simpler Web API. This article is not focused on comparing Web Service and Web API, but rather it focuses on Exception Handling in Web API.

By default,  the most common exception that an API Controller raises are translated into an HTTP Status Code 500 (Internal Server Error) (HTTP Status Code ). But what if we want to customize the Error Code ? There are couple of ways to achieve it, the first part of this article focuses on Exception Filters.
An Exception Filter is probably the easiest way to handle the exception efficiently and it would handle any exception which the controller throws except for the HttpResponseException (Why HttpResponseException is not handled by Exception Filter will be discussed later).
The simplest way to create you own customized Exception Filter is to derive from ExceptionFilterAttribute Class under System.Web.Http.Filters namespace and override the OnException Method
An Example of Exception Filter is shown below.
public class DemoExceptionFilter : ExceptionFilterAttribute
{
public override void OnException( HttpActionExecutedContext ExecutedContext)
{
if (ExecutedContext.Exception is NotImplementedException)
{
ExecutedContext.Response = new HttpResponseMessage (HttpStatusCode.ServiceUnavailable);
ExecutedContext.Response.ReasonPhrase += " : Function Not Implemented";
}
base.OnException(ExecutedContext);
}
}
The code is pretty self explanatory. I have modified all the NotImlementedException to change the Http Status Code to 503 (Service Unavailable). I have also appended “Function Not Implemented”  message to the Reason Phrase . The next obvious step is to ensure our Exception Filter is used by the WebAPI Pipeline. To ensure that the DemoExceptionFilter is used globally, all we need to do is to add it to the list of filters in WebApiConfig. We use the Filters.Add Method in HttpConfiguration to do the same. For Example,
	public static void Register(HttpConfiguration config)
        {
            // Web API configuration and services

            // Web API routes
            config.MapHttpAttributeRoutes();

            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );

            config.Filters.Add(new ExceptionManagement.DemoExceptionFilter());
        }
That’s it !!!. Now every Exception your APIController throws , with the exception of HttpResponseException , would have to go through your DemoExceptionFilter. To test the code, I have thrown an exception from my controller as seen in example below.
    public class ValuesController : ApiController
    {
        // GET api/values
        public IEnumerable  Get()
        {
            throw new NotImplementedException ();
        }

        // GET api/values/5
        public string Get( int id)
        {
            return "value" ;
        }
     }
     
Now run your application and check the response in Fiddler.
 NotImplemented
Wasn’t that easy ? Yes, but Exception Filters has its own short-comings, which would be explained in the next part. Happy Coding !!

Hello World in Ext JS and ASP.Net MVC4

Javascript based frameworks has been evolving of late and one of the prominent among them is External Javascript, better known as Ext JS. Unlike some of its competitors like Angular JS, Ext JS distinguishes itself with a rich suite of UI components. It is cross browser compatible. I am delving more into details of Ext JS, and as always, jumping right into the code.

For this post, we would be referring the online version of the ExtJS libraries.

Ok Tim to do some coding. Let’s start by creating a MVC application in Visual Studio.

image

Now open your ‘\Shared\_Layout.cshtml’ and add the following code in the ” section.

These lines refers and includes the CSS styles and ExtJS library. Like mentioned earlier in the post, we would be referring on-line version in this tutorial.  The next step is to add the script to call our Hello World Message box.

 

        Ext.onReady( function () {

            Ext.Msg.alert( “Alert” , “Hello world!” );

        });

 

Entire ‘ Section would look like

image

That’s it. You are done. Kick off the application and you will see your first application in ExtJS using Asp.Net

image