0

I have a local jpg file ("C:\Life\Banners\1.jpg").
How can I return an accessible URL of this file? e.g.:
http://MyServer/Banners/1.jpg

I tried using the following:

HostingEnvironment.MapPath("~/Images/HT.jpg");
HostingEnvironment.MapPath("C:\Life\Banners\1.jpg");

But both of them returns null

My WebAPI Controller looks like this:

namespace WebServiceAPI
{
    [EnableCors(origins: "*", headers: "*", methods: "*")]
    [RoutePrefix("api/Banner")]
    public class BannerController : ApiController
    {
        [Route("GetBanner")]
        [HttpGet]
        public Banner GetBanner()
        {
            return BannerBL.GetBanner();
        }
    }
}

public class Banner
    {
        public int bannerId;
        public string url;
        public string icon;
        public string link;
    }
Dor Cohen
  • 16,769
  • 23
  • 93
  • 161
  • Possible duplicate of [Can an ASP.NET MVC controller return an Image?](http://stackoverflow.com/questions/186062/can-an-asp-net-mvc-controller-return-an-image) – Peter B Nov 18 '16 at 15:11
  • 1
    Note that MVC and Web API are very similar, meaning the solution mentioned above for MVC should also work for a Web API project with little or no changes. – Peter B Nov 18 '16 at 15:12
  • @PeterB The name 'Server' does not exist in the current – Dor Cohen Nov 18 '16 at 15:14
  • @PeterB which DLL I need to import? – Dor Cohen Nov 18 '16 at 15:14
  • What role does the Web Api have in this? If you have a Web Api, presumably you send something TO the Api and then expect the Api to give you something back. What do you send as input to the Web Api? – user1429080 Nov 18 '16 at 15:17
  • @user1429080 I have a GET method, I've added the Method to the question – Dor Cohen Nov 18 '16 at 15:18

1 Answers1

0

An MVC action method should always return an ActionResult type, or one of its subclasses.
Your class Banner is not such a subclass, it is an object of a type that MVC can not use to create a Web Response from.

This should work (put it in e.g. MyApiController.cs):

[HttpGet]
public ActionResult GetBanner()
{
    var path = @"C:\Life\Banners\1.jpg";  // The @ allows us to use single backslashes
    return File(path, "image/jpeg");      // This returns a FileResult object
}

And the URL will then be:

http://MyServer/MyApi/GetBanner

Once you get this working you can try to integrate it with your Banner class.

Peter B
  • 22,460
  • 5
  • 32
  • 69
  • Thanks, What is File class? which DLL should I use? currently the code isn't compiling – Dor Cohen Nov 19 '16 at 16:51
  • When using FileResult I'm getting the following response which contains the file local path, which isn't accessible from client { "FileName": "C:\\Life\\Banners\\1.jpg", "ContentType": "image/jpeg", "FileDownloadName": "" } – Dor Cohen Nov 19 '16 at 17:09