【问题标题】:How to return html page from WebApi action?如何从 WebApi 操作返回 html 页面?
【发布时间】:2016-11-01 11:57:43
【问题描述】:

我正在寻找一个 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");
}

如果我用错了,有什么更好的方法,你能给我举个例子吗?

带有 .NET 4.52 的 WebApi 2

编辑:嗯,改进了它,但返回的是 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"]}]}

【问题讨论】:

    标签: c# iis asp.net-web-api


    【解决方案1】:

    对于 ASP.NET Core(不是 ASP.NET Standard),如果它是静态 html 文件(看起来像),请使用静态资源选项:

    Static files in ASP.NET Core

    【讨论】:

    • 看起来这是针对 Asp.Net Core 的。请原谅我不太明白在哪里更改 WebApi 代码以提供静态文件。我没有 Configure 或 WebHostBuilder 方法。
    • 这很有用,因为越来越多(像我一样)正在搜索 Core。但是稍微解释一下链接会很好。
    【解决方案2】:

    执行此操作的一种方法是将页面作为字符串读取,然后在内容类型为“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;
    }
    

    【讨论】:

    • "your path to index.html" 需要是绝对路径吗?
    猜你喜欢
    • 2018-12-07
    • 1970-01-01
    • 1970-01-01
    • 2020-01-12
    • 1970-01-01
    • 2013-07-23
    • 2011-12-28
    • 2020-03-02
    • 1970-01-01
    相关资源
    最近更新 更多