How to return html page from WebApi action?

喜欢而已 提交于 2019-12-30 02:36:07

问题


I'm looking for a WebApi example where the default route will return a given html page to the caller. I've got the route and action set up as follows. I just want to send him the index.html page, not redirect, because he's in the right place.

http://localhost/Site      // load index.html

// WebApiConfig.cs
config.Routes.MapHttpRoute(
    name: "Root",
    routeTemplate: "",
    defaults: new { controller = "Request", action = "Index" }
);

// RequestControlller.cs
    [HttpGet]
[ActionName("Index")]
public HttpResponseMessage Index()
{
    return Request.CreateResponse(HttpStatusCode.OK, "serve up index.html");
}

If I"m using this wrong, what's the better approach and can you point me to an example?

WebApi 2 with .NET 4.52

Edit: Hmm, improved it, but getting json header back instead of page content.

public HttpResponseMessage Index()
{
    var path = HttpContext.Current.Server.MapPath("~/index.html");
    var content = new StringContent(File.ReadAllText(path), Encoding.UTF8, "text/html");
    return Request.CreateResponse(HttpStatusCode.OK, content);
}

{"Headers":[{"Key":"Content-Type","Value":["text/html; charset=utf-8"]}]}

回答1:


One way to do this is to read the page as a string and then send it in a response of content type "text/html".

Add namespace IO:

using System.IO;

In the controller:

[HttpGet]
[ActionName("Index")]
public HttpResponseMessage Index()
{
    var path = "your path to index.html";
    var response = new HttpResponseMessage();
    response.Content =  new StringContent(File.ReadAllText(path));
    response.Content.Headers.ContentType = new MediaTypeHeaderValue("text/html");
    return response;
}



回答2:


For ASP.NET Core (not ASP.NET Standard) then if it's a static html file (which it looks like), use the static resource options:

Static files in ASP.NET Core



来源:https://stackoverflow.com/questions/38105305/how-to-return-html-page-from-webapi-action

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!