2017-02-15 27 views
1

我正在使用.net WebApi使用JSON数据公开不同的端点。现在我需要一个特定的端点返回HTML页面。我已经像这样实现了它。带有图像的HTML页面使用.net WebApi

[HttpGet] 
[Route("htmlPage/{htmlPageId}")] 
public HttpResponseMessage GetHtmlPage(string htmlPageId) { 
    string rawHtml = m_logic.GetHtmlPageById(htmlPageId); 
    HttpResponseMessage response = new HttpResponseMessage {Content = new StringContent(rawHtml)}; 
    response.Content.Headers.ContentType = new MediaTypeHeaderValue("text/html"); 
    return response; 
} 

我面对的问题是当HTML页面有一些图像时。我不知道如何将它们公开,因为现在当我从浏览器调用我的端点时,发现404未找到错误。我在我的项目中有一个文件夹,这些图像和一些Javascript脚本必须返回。

我该怎么做?

编辑: 这是我的HTML的一部分

<html lang=\"en\"> 
    <head> 
    <title> Simplest HTML </title> 
    <meta name=\"description\" content=\"The Html served\"> 
    <meta name=\"author\" content=\"acostela\"> 
    <script type="text/javascript" src="./public/scripts/my-api.js"></script> 
    </head> 
    <body> 
    <h1> The first Simplest html served!!</h1> 
    <img src="./public/img/success.jpg"/></br></br> 
    </body> 
</html> 

我的文件夹结构如下

-->Html 
    | 
    | 
     ---> myFirstHtml.html 
    | 
    | 
     ---> public 
      | 
      | 
      ---> img 
      | | 
      | | 
      | ---> success.jpg 
      | 
      | 
      ---> scripts 
       | 
       | 
       ---> my-api.js 
+0

不要使用./但〜正如你可以在我的例子中看到 – Ygalbel

+0

@Ygalbel我试过你的解决方案,但我得到了同样的错误。 GET http:// localhost:8888/endpoint /〜img/success.jpg 404(Not Found) – acostela

+0

你的结构应该是localhost:8888/public/img/sucess.jpg – Ygalbel

回答

0

最后我解决它。我添加了一个使用owin + katana的静态文件服务器中间件。

我用这个

public void Configuration(IAppBuilder application) 
    { 
     //Other webApi configuration 
      application.UseFileServer(new FileServerOptions() 
      { 
       RequestPath = new PathString("/html/public"), 
       FileSystem = new PhysicalFileSystem(@"../../../MyProject/html/public"), 
      }); 

现在自动所有图像的脚本和文件都在公共场合通过我的WebAPI请求我的html页面供应改变了我的启动类。

这段代码是如何将我的http请求“/ html/public”转换为我在PhysicalFileSystem中指定的真实文件系统路径。

希望这可以帮助任何人。

0

的WebAPI可提供静态文件。

所以你只需要在你的HTML文件中设置正确的链接。

例如:

enter image description here

<img>将是这样的:

<img src="~/Content/img/email-icon.png" />

+0

这不起作用。我得到同样的错误。 GET 404(未找到) – acostela

+0

您尝试访问哪个网址?你能分享一部分html代码吗? – Ygalbel

+0

我已更新我的问题。谢谢! :) – acostela

相关问题