Contents tagged with WEBAPI

  • Using Unity with ASP.NET WEB API Controller

    518 comments

    Support for Ioc containers is backed into ASP.NET WEB API and uses the service locator pattern dependency resolver by default.

    the default service locator implements the IDependencyResolver interface. This interface has two methods.

    • GetService: Creates one instance of a specified type.
    • GetServices: Create a collection of objects of a specified type.

    in order to use Microsoft Unity framework with ASP.NET WEB API we need to map these to methods to Resolve and ResolveAll methods of Utity. to do so first add the following method to your global.asax.cs or your bootstrapper class

            Public static void RegisterDependencies(IUnityContainer container)
            {
     
                GlobalConfiguration.Configuration.ServiceResolver.SetResolver(
                    t =>
                    {
                        try
                        {
                            return container.Resolve(t);
                        }
                        catch (ResolutionFailedException)
                        {
                            return null;
                        }
                    },
                    t =>
                    {
                        try
                        {
                            return container.ResolveAll(t);
                        }
                        catch (ResolutionFailedException)
                        {
                            return new List<object>();
                        }
                    });
            }

    this is the method which maps the GetService and GetServices methods to Resolve and ResolveAll methods.

    the next and final step is to plug in this method to the framework. to do so you just need to call this method from the method in which you construct your unity container. in my case I create a separate method to take care of this:

            private static IUnityContainer BuildUnityContainer()
            {
                var container = new UnityContainer();
                RegisterMappers(container);
                RegisterDependencies(container);
                container.RegisterControllers();
                DependencyResolver.SetResolver(new UnityDependencyResolver(container));
                return container;
            }

    and you are done. you should be able to use your Ioc container with ASP.NET WEB API now.

    Written by vahid

    Sunday, April 15, 2012 at 10:40 AM

    Tagged with , ,

  • Hosting ASP.NET WEB API

    307 comments

    You may want to host you HTTP Service i.e. ASP.NET WEB API in a console app. well it can be easily done.

    to show this lets create a console app and add reference to the following assemblies:

    System.Web
    System.Web.Http
    System.Web.Http.Common
    System.Web.Http.SelfHost
    System.Web.Http.WebHost
    System.Net;
    System.Net.Http.Formatting;
    System.Net.Http.Headers;
     

    this step is optional but for just touching on Json.net I am going to install Json.net using Nuget.

    image

     

    Now lets add a CarInfo class to return it in our controller

       1:      public class CarInfo
       2:      {
       3:          private readonly DateTime releaseDate = DateTime.UtcNow;
       4:          private readonly Dictionary<int, string> availableColors = new Dictionary<int, string>  
       5:            {         
       6:            { 1, "yellow"},   
       7:            { 2, "red" },   
       8:            { 3, "black" }, 
       9:            };
      10:   
      11:          public string Name
      12:          {
      13:              get
      14:              {
      15:                  return "BMW X6";
      16:              }
      17:          }
      18:          public DateTime ReleaseDate { get { return releaseDate; } }
      19:          public IDictionary<int, string> AvailableColors { get { return availableColors; } }
      20:      }

     

    And let’s create our home controller as bellow:

     

       1:      public class HomeController : ApiController
       2:      {
       3:          // GET /api/<controller>
       4:          public CarInfo Get()
       5:          {
       6:              return new CarInfo();
       7:          }
       8:      }

    as you see our controller has got just one method which responds to the Get request.

    we also need a little helper class to integrate JSon.net to our application. please note as mentioned above using Json.net is optional.

     

      public class JsonNetFormatter : MediaTypeFormatter
        {
            private readonly JsonSerializerSettings jsonSerializerSettings;
     
            public JsonNetFormatter(JsonSerializerSettings jsonSerializerSettings)
            {
                this.jsonSerializerSettings = jsonSerializerSettings ?? new JsonSerializerSettings();
                SupportedMediaTypes.Add(new MediaTypeHeaderValue("application/json"));
                Encoding = new UTF8Encoding(false, true);
            }
     
            protected override bool CanReadType(Type type)
            {
                return type != typeof(IKeyValueModel);
            }
     
            protected override bool CanWriteType(Type type)
            {
                return true;
            }
     
            protected override Task<object> OnReadFromStreamAsync(Type type, Stream stream, 
    HttpContentHeaders contentHeaders, FormatterContext formatterContext)
            {
                var serializer = JsonSerializer.Create(this.jsonSerializerSettings);
     
                return Task.Factory.StartNew(() =>
                {
                    using (var streamReader = new StreamReader(stream, Encoding))
                    {
                        using (var jsonTextReader = new JsonTextReader(streamReader))
                        {
                            return serializer.Deserialize(jsonTextReader, type);
                        }
                    }
                });
            }
     
            protected override Task OnWriteToStreamAsync(Type type, object value, Stream stream, 
    HttpContentHeaders contentHeaders, FormatterContext formatterContext, TransportContext transportContext)
            {
                var serializer = JsonSerializer.Create(this.jsonSerializerSettings);
     
                return Task.Factory.StartNew(() =>
                {
                    using (var jsonTextWriter = 
    new JsonTextWriter(new StreamWriter(stream, Encoding)) { CloseOutput = false })
                    {
                        serializer.Serialize(jsonTextWriter, value);
                        jsonTextWriter.Flush();
                    }
                });
            }
        }

    ok it’s time to create actual host to host our service. you just need to add few lines of code to the main method of the program

            static void Main(string[] args)
            {
                // Set up server configuration    
                HttpSelfHostConfiguration config = new HttpSelfHostConfiguration("http://localhost:8081");
                config.Routes.MapHttpRoute("Default", "{controller}", new { controller = "Home" });
     
               
                JsonSerializerSettings serializerSettings = new JsonSerializerSettings();
                serializerSettings.Converters.Add(new IsoDateTimeConverter());
                config.Formatters[0] = new JsonNetFormatter(serializerSettings);
     
                // Create server   
                var server = new HttpSelfHostServer(config);
     
                // Start listening   
                server.OpenAsync().Wait();
                Console.ReadLine();
            }

    to test the application open Fiddler and create a request as below:

    image

    basically you need to set the address to http://localhost:8081/Home and content-type to Content-Type: application/json; charset=utf-8. once you create the request click on execute and you should be getting the following response back

    image

    as you see we get Json representation of the CarInfo object.

    it was quit simple, wasn’t it?

    Written by vahid

    Sunday, March 18, 2012 at 10:26 PM

    Tagged with ,

  • Make a call to a JSON/XML ASP.Net WEB API from server code

    913 comments

    There is plenty of articles out there on how to make a ajax call to a asp.net web api service. but what if you want to make a call to the same service from a server code? this can happen because of various reasons like when you want to offer a service and use IP validation.

    anyway this is quite simple to call a service exposed by ASP.net WEB API either using JSON or XML. and it is like calling a WCF or XML web service from a server side code without adding a reference to the service.

    Lets assume that our ASP.net WEB API provide a service to and and return flights using a given FlightSearchRequest object.

    FlightSearchRequest

     1:     public class FlightSearchRequest
     2:     {
     3:         public string DepartureAirportCode { get; set; }
     4:  
     5:         public string ArrivalAirportCode { get; set; }
     6:     }

    WEB API Method

     1:         [HttpPost]
     2:         public IEnumerable<Flight> GetFlights(FlightSearchRequest flightRequest)
     3:         {
     4:  
     5:             return new List<Flight>
     6:                 {
     7:                     new Flight { Id=1, AirlineCode = "EK", Price = 350 }, 
     8:                     new Flight { Id=2, AirlineCode = "LX", Price = 280 },
     9:                 };
     10:         }

    and here is the code to call the service:

    Using JSON

     1:             HttpWebRequest request;
     2:             HttpWebResponse hwResponse;
     3:             string url = "http://127.0.0.1:26030/api/MyAPI/GetFlights";
     4:             string responseBody = string.Empty;
     5:             string requestBody = 
    			"[{\"DepartureAirportCode\":\"MEL\",\"ArrivalAirportCode\":\"LHR\"}]";
     6:            
     7:                 byte[] byteData = UTF8Encoding.UTF8.GetBytes(requestBody.ToString());
     8:                 request = (HttpWebRequest)HttpWebRequest.Create(url);
     9:                 request.ContentType = "application/json;charset=utf-8";
     10:                 request.UserAgent = 
    	"Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0; BOIE9;ENUS)";
     11:                 request.Accept = "*/*";
     12:                 request.Method = "POST";
     13:                 request.ContentLength = byteData.Length;
     14:                 
     15:                 // Write data 
     16:                 using (Stream postStream = request.GetRequestStream())
     17:                 {
     18:                     postStream.Write(byteData, 0, byteData.Length);
     19:                 }
     20:  
     21:                 // Get response 
     22:                 using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
     23:                 {
     24:                     // Get the response stream 
     25:                     using (var reader = new StreamReader(response.GetResponseStream()))
     26:                     {
     27:                         responseBody = reader.ReadToEnd();
     28:                     }
     29:                 }

     

    to make the same call using XML you just need to change the ContentType to application/xml and also change the request body to an xml format

    Using XML

     1:             HttpWebRequest request;
     2:             HttpWebResponse hwResponse;
     3:             string url = "http://127.0.0.1:26030/api/MyAPI/GetFlights";
     4:             string responseBody = string.Empty;
     5:             string requestBody = 
    				"<Product><Id>6</Id><Name>Jackson</Name></Product>";         
     6:                 byte[] byteData = UTF8Encoding.UTF8.GetBytes(requestBody.ToString());
     7:                 request = (HttpWebRequest)HttpWebRequest.Create(url);
     8:                 request.ContentType = "application/xml;charset=utf-8";
     9:                 request.UserAgent = 
    	"Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0; BOIE9;ENUS)";
     10:                 request.Accept = "*/*";
     11:                 request.Method = "POST";
     12:                 request.ContentLength = byteData.Length;
     13:                 
     14:                 // Write data 
     15:                 using (Stream postStream = request.GetRequestStream())
     16:                 {
     17:                     postStream.Write(byteData, 0, byteData.Length);
     18:                 }
     19:  
     20:                 // Get response 
     21:                 using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
     22:                 {
     23:                     // Get the response stream 
     24:                     using (var reader = new StreamReader(response.GetResponseStream()))
     25:                     {
     26:                         responseBody = reader.ReadToEnd();
     27:                     }
     28:                 }

    now the more I play with WEP API the more I like it Smile

    Written by vahid

    Monday, March 12, 2012 at 1:25 PM

    Tagged with ,

  • ASP.Net WEB API VS WCF Service

    343 comments

    Well as soon as i heard and read about asp.net web api, i was very excited about it but in between i had that mmmmm moment. i was like, this is great but what about WCF? I am not going to create any WCF services anymore?

    so I had think again about it but could not find any concrete answer as these two are overlapping in many areas. so I had to do a bit more R&D about the differences and I came across this blog post from Matt Milner.

    the post has got very fair point on when to use WCF services and when to use ASP.net web api. but in nutshell I think for most of our feature service development for web –over http-, we are going to use ASP.net web api and it kind of make sense as it’s much easier to setup and use.

    here is blog post address:

    http://mattmilner.com/Milner/Blog/post/2012/02/28/WebAPI-or-WCF.aspx

    Written by vahid

    Sunday, March 11, 2012 at 11:00 PM

    Tagged with , ,