0

Noob question. I have a project with a self-hosted Web Api. I'm using the RazorEngine package so that I can serve up HTML pages using the views/razor scheme.

Within the HTML page there are links to .css, .JS, and images. How does the page get these embedded resources?

As I understand it, http://localhost:8080/api/home in the browser causes the project to 'call' the page at /Views/Home.html and pass through the Value object. This results in HTML appearing in the browser rather than the usual JSON/XML that you normally get with WebAPi.

For the page to retrieve the embedded javascript, I guess I would create another WebApi controller that would respond to the URL, but how do I get it to transmit the javascript page? Ie how do I get it to look in a folder called 'Scripts' and not 'Views', not attempt to convert to HTML, and not bother with an associated model?

public class HomeController : ApiController
{

    //http://localhost:8080/api/home
    public Value GetValues()
    {
        return new Value() { Numbers = new int[] { 1, 2, 3 } };
    }
}


[View("Home")]     
public class Value
{
    public int[] Numbers { get; set; }
}

home.cshtml...

<html>
<head>
     <script src="/Scripts/script1.js"></script>
</head>
<body>
     <img src="/Images/image1.png">
    ....
</body>
</html>
spiderplant0
  • 3,872
  • 12
  • 52
  • 91
  • Looks like you are looking for a way to download the files (javascript or css)...if yes, you can take a look at this: http://stackoverflow.com/questions/9541351/returning-binary-file-from-controller-in-asp-net-web-api – Kiran Feb 04 '14 at 02:00
  • You can also do it like this https://github.com/darrelmiller/HypermediaApiSite/blob/master/HypermediaApiContent/css/StylesheetsController.cs – Darrel Miller Feb 04 '14 at 14:32
  • @DarrelMiller, thanks for your helsp - I've posted my complete solution – spiderplant0 Feb 05 '14 at 22:44

1 Answers1

0

In case anyone else has this issue, this is how I did it in the end....

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web.Http;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Diagnostics;
using WebApiContrib.Formatting.Html;
using System.IO;
using System.Net;
using System.Drawing;
using System.Resources;
using System.Reflection;
using System.Text.RegularExpressions;


namespace Owin_Test1.Controllers
{


    public class PageResourcesController : ApiController
    {

        //
        // An HTML page will have references to css, javascript and image files
        // This method supplies these file to the browser
        // These files are saved in the Visual Studio project as linked resources
        // Make sure the resources are names correctly (and correct case) i.e.:
        // <fileName> = <resourceName>.<fileExtension>
        // http://localhost:8080/api/PageResources/<fileName>
        // The fileExtension is used to determine how to extract & present the resource
        // (Note, <filename> is the reference in the HTML page 
        // - it needed be the same as the name of the actual file.)
        //

        public HttpResponseMessage Get(string filename)
        {
            String projectName = "Owin_Test1";

            //Obtain the resource name and file extension
            var matches = Regex.Matches(filename, @"^\s*(.+?)\.([^.]+)\s*$");
            String resourceName = matches[0].Groups[1].ToString();
            String fileExtension = matches[0].Groups[2].ToString().ToLower();
            Debug.WriteLine("Resource: {0} {1}", 
                resourceName, 
                fileExtension);

            //Get the resource
            ResourceManager rm = new ResourceManager(
                projectName + ".Properties.Resources",
                typeof(Properties.Resources).Assembly);
            Object resource = rm.GetObject(resourceName);

            ImageConverter imageConverter = new ImageConverter();
            byte[] resourceByteArray;
            String contentType;

            //Generate a byteArray and contentType for each type of resource
            switch (fileExtension)
            {
                case "jpg":
                case "jpeg":
                    resourceByteArray = (byte[])imageConverter.ConvertTo(resource, typeof(byte[]));
                    contentType = "image/jpeg";
                    break;

                case "png":
                    resourceByteArray = (byte[])imageConverter.ConvertTo(resource, typeof(byte[]));
                    contentType = "image/png";
                    break;

                case "css":
                    resourceByteArray = Encoding.UTF8.GetBytes((String)resource);
                    contentType = "text/css";
                    break;

                case "js":
                    resourceByteArray = Encoding.UTF8.GetBytes((String)resource);
                    contentType = "application/javascript";
                    break;

                case "html":
                default:
                    resourceByteArray = Encoding.UTF8.GetBytes((String)resource);
                    contentType = "text/html";
                    break;
            }

            //Convert resource to a stream, package up and send on to the browser
            MemoryStream dataStream = new MemoryStream(resourceByteArray);
            HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK);
            response.Content = new StreamContent(dataStream);
            response.Content.Headers.ContentType = new MediaTypeHeaderValue(contentType);

            return response;
        }

    }
}
spiderplant0
  • 3,872
  • 12
  • 52
  • 91