中的静态文件
我正在寻找一个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");
}
如果我"使用了这个错误,更好的方法是什么,您可以指出我的例子?
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"]}]}
做到这一点的一种方法是将页面读为字符串,然后以内容类型的响应" text/html"发送。
添加名称空间IO:
using System.IO;
在控制器中:
[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;
}
for asp.net core(不是ASP.NET标准),则如果它是静态HTML文件(看起来像它),请使用静态资源选项:
asp.net core