Posted By : Murugan Andezuthu Dharmaratnam
Posted On : 13 December 2014
Keywords : web api return file, Web API File, Web API return Exce, Responsel

Web API : Return File From Server

I was looking to return an excel file from the server when use clicks on a link. Here is a code snippet

Sample Code




        public HttpResponseMessage Get()
        {
            var path = @"C:\works\murugan.txt";
            HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK);
            var stream = new FileStream(path, FileMode.Open);
            result.Content = new StreamContent(stream);
            result.Content.Headers.ContentType =
                new MediaTypeHeaderValue("application/octet-stream");
            ContentDispositionHeaderValue oContentDispositionHeaderValue = new ContentDispositionHeaderValue("attachment");
            oContentDispositionHeaderValue.FileName = "Murugan.txt";
            result.Content.Headers.ContentDisposition = oContentDispositionHeaderValue;
            return result;
        }


Murugan Andezuthu Dharmaratnam

Murugan is a technology leader with 14 years of hands-on experience in full life cycle systems design, development, implementation, and management. In addition to systems design and development, his core competencies include cloud design and architecture, interactive web applications and websites development, mobile computing, and Healthcare Information Technology. His experience is very diverse with a broad range of technologies within multiple industry settings including private, public, and non-profit. Coupled with his technology expertise, Murugan is a well-organized, result-oriented, and a highly analytical leader with proven track record in developing and implementing very complex systems.