如何获取自托管Web Api来获取链接内容?

时间:2014-02-04 01:00:58

标签: asp.net-web-api

Noob问题。我有一个带有自托管Web Api的项目。我正在使用RazorEngine包,以便我可以使用views / razor方案提供HTML页面。

在HTML页面中,有指向.css,.JS和图像的链接。页面如何获取这些嵌入式资源?

据我了解,浏览器中的http://localhost:8080/api/home会导致项目在/Views/Home.html“调用”页面并通过Value对象。这导致HTML出现在浏览器中,而不是您通常使用WebAPi获得的常用JSON / XML。

对于检索嵌入式javascript的页面,我想我会创建另一个响应URL的WebApi控制器,但是如何让它传输javascript页面呢?即如何让它在一个名为“Scripts”而不是“Views”的文件夹中查找,而不是尝试转换为HTML,而不是打扰相关模型?

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>

1 个答案:

答案 0 :(得分:0)

如果其他人有这个问题,我最终会这样做....

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;
        }

    }
}