如何从WebApi动作返回html页面?

dis*_*r-5 24 c# iis asp.net-web-api

我正在寻找一个WebApi示例,其中默认路由将给定调用者返回给定的html页面.我的路线和行动设置如下.我只想向他发送index.html页面,而不是重定向,因为他在正确的位置.

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");
}
Run Code Online (Sandbox Code Playgroud)

如果我使用这个错误,那么更好的方法是什么,你能指点我一个例子吗?

WebApi 2与.NET 4.52

编辑:嗯,改进了它,但得到了json头而不是页面内容.

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"]}]}
Run Code Online (Sandbox Code Playgroud)

Mar*_*und 38

一种方法是将页面作为字符串读取,然后将其发送到内容类型为"text/html"的响应中.

添加命名空间IO:

using System.IO;
Run Code Online (Sandbox Code Playgroud)

在控制器中:

[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;
}
Run Code Online (Sandbox Code Playgroud)