EcSolvo.RestHelper Nuget

Recently I have started working on a Nuget Package for providing a is a sleek and simple Wrapper library for providing simple access to Rest API, by hiding away the complexities of HTTPClient Class.Named EcSolvo.RestHelper it is particularly designed to work along with Xamarin PCL Projects

You can follow and contribute to the Nuget in Github : Link to GitHub Repository

Follow updates on Nuget : Link To Nuget

Advertisements

Unit Test for Methods that Call Web API

HttpClient helps you interact with your Rest API’s through its asynchronous methods such as GetAsync. But on a TDD environment, it could become a challenge on how you could write Unit Test cases for a method that invokes the API via GetAsync and ensure that your call successfully invokes the API (considering your API sits in another server and calling it your unit tests would not be ideal). The way I approached this by creating a self hosted API within the Unit Test Project and make the Test Method calls to the API.

The first step was to use Open Web Interface for .Net (or OWIN) to self host an API. Microsoft has put on an extremely useful link for the purpose. Following become by code to configure the API.

 public class WebApiStartup
 {
 // This code configures Web API. The Startup class is specified as a type
 // parameter in the WebApp.Start method.
 public void Configuration(IAppBuilder appBuilder)
 {
 // Configure Web API for self-host. 
 HttpConfiguration config = new HttpConfiguration();
 config.Routes.MapHttpRoute(
 name: "DefaultApi",
 routeTemplate: "api/{controller}/{id}",
 defaults: new { id = RouteParameter.Optional }
 );

 appBuilder.UseWebApi(config);
 }
 }
 The Next Step is go ahead and create the Test Controller, which would be hosting all your api methods.
 [RoutePrefix("api/user")]
public class UserController : ApiController
{
[HttpGet]
[Route("")]
public bool NoParamBooleanResponse()
{
return true;
}
}

Finally, its time to go ahead and write the Test Methods.

 private const string _BaseAddress = "http://localhost:9388/";

[TestMethod]
public async Task CallNoParamAPI_ServerRunning_GetResponseTrue()
{

#region Arrange

var resourceURL = "api/user/SingleParamBooleanResponse";
var restHelper = new RestHelper(_BaseAddress);
bool result;
#endregion

#region Act
using (WebApp.Start<WebApiStartup>(_BaseAddress))
{
result = await restHelper.ExecuteAsync<bool>(resourceURL,HttpMethod.Get);
}
#endregion

#region Assert
Assert.IsTrue(result);
#endregion

}

In the above example, my  restHelper.ExecuteAsync() method invokes the GetAsync Method of HttpClient.

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<Type, HttpStatusCode>();
 this.ExceptionDictionary.Add(typeof(NotImplementedException), HttpStatusCode.ServiceUnavailable);
 this.ExceptionDictionary.Add(typeof(ArgumentOutOfRangeException), HttpStatusCode.BadRequest);
 }
 public IDictionary<Type, HttpStatusCode> 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 <string > 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 !!