Blogger Widgets
  • Sharing Photos using SignalR
  • TFS Extenstion - allows copy work items between projects
  • Displaying jquery progressbar with ajax call on a modal dialog
  • Managing windows services of a server via a website
  • Exploring technologies available to date. TechCipher is one place that any professional would like to visit, either to get an overview or to have better understanding.

Search This Blog

Wednesday 25 September 2013

Using ASP.NET Web API for streaming pictures

ASP.NET Web API 2.0 provides various new features and one of which is Attribute Routing. Attribute routing allows custom configuration for routing by assigning attribute to the web method.

Get latest version of ASP.NET Web API 2.0 via Nuget package
Install-Package Microsoft.AspNet.WebApi.WebHost
Update WebApiConfig to include config.MapHttpAttributeRoutes()
 public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            config.MapHttpAttributeRoutes();

            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );
        }
    }
The [HttpGet] attribute defines an HTTP GET method. Now create RESTful endpoint using web api
[HttpGet("api/invoice/scan/{id}")]
public HttpResponseMessage GetScannedInvoiceById(string id)
{
 HttpResponseMessage result = new HttpResponseMessage();
 string isPath = GetInoviceScanPath(id);
        result.Content = new StreamContent(new FileStream(isPath, FileMode.Open));
 result.Content.Headers.ContentType = new MediaTypeHeaderValue("image/png");
 return result;
}
http://localhost/csharptechies/api/invoice/scan/1908765 will now get the image as HttpResponseMessage.

Apart from using attributes to define an uri for controller methods, Route Prefixes can be defined as a controller attribute that will become base uri for for all of the controller methods.

Do you realize if it weren't for Edison we'd be watching TV by candlelight.
Al Boliska

1 comments:

Copyright © 2013 Template Doctor . Designed by Malith Madushanka - Cool Blogger Tutorials | Code by CBT | Images by by HQ Wallpapers