【问题标题】:Trying to return HTML in an ActionResult results in a HTTP 406 Error尝试在 ActionResult 中返回 HTML 会导致 HTTP 406 错误
【发布时间】:2017-12-02 07:42:31
【问题描述】:

我正在尝试在ActionResult 中返回 HTML。我已经试过了:

[Produces("text/html")]
public ActionResult DisplayWebPage()
{
    return Content("<html><p><i>Hello! You are trying to view <u>something!</u></i></p></html>");
}

这在&lt;iframe&gt; 中不显示任何内容。我试过了:

[Produces("text/html")]
public string DisplayWebPage()
{
    return HttpUtility.HtmlDecode("<html><p><i>Hello! You are trying to view <u>something!</u></i></p></html>");
}

Microsoft Edge 给我以下消息:

HTTP 406 错误
此页面不是我们的语言 Microsoft Edge 无法显示此页面,因为它不是可以显示的格式。

Firefox 和 Chrome 拒绝显示任何内容。我也试过HtmlEncode 和普通的ActionResult。这是我的视图中我的&lt;iframe&gt; 的片段:

<div class="row">
    <div class="col-sm-12">
        <iframe src="/Home/DisplayWebPage" class="col-sm-12"></iframe>
    </div>
</div>

为什么我没有收到任何结果?我是不是做错了什么?

【问题讨论】:

  • 在 mvc-5 中工作正常(目前无法在 core-mvc 中测试)。您是否尝试过删除 [Produces] 属性?
  • 尝试添加body标签
  • 您的 html 内容缺少结构,这就是导致错误的原因尝试发送有效的 html 内容
  • 我试过删除[Produces],还是不行
  • 即使我为 HTML 页面使用了正确的结构,它仍然无法呈现。

标签: c# asp.net-mvc iframe asp.net-core-mvc


【解决方案1】:

Produces("text/html") 不会有任何效果,因为没有内置的 HTML 输出格式化程序。

要解决您的问题,只需明确指定内容类型:

public ActionResult DisplayWebPage()
{
    return Content("<html><p><i>Hello! You are trying to view <u>something!</u></i></p></html>", "text/html");
}

另一种选择是将您的操作的返回类型更改为string,并通过Accept 标头请求text/html 格式。详情请见Introduction to formatting response

【讨论】:

  • 是的!它完美地工作!我应该尝试将text/html 作为Content 的参数传递。谢谢!
【解决方案2】:

有两种方法可以做到这一点: 1. 将操作更新为:

public IActionResult Index()
{
    var content = "<html><body><h1>Hello World</h1><p>Some text</p></body></html>";
    return new ContentResult()
    {
        Content = content,
        ContentType = "text/html",
    };
}

2. 将操作更新为:

[Produces("text/html")]
public IActionResult Index()
{
    return Ok("<html><p><i>Hello! You are trying to view <u>something!</u></i></p></html>");
}

并将 startup.cs 中的 AddMvc 行更新为:

services.AddMvc(options => options.OutputFormatters.Add(new HtmlOutputFormatter()));

HtmlOutputFormatter 在哪里:

public class HtmlOutputFormatter : StringOutputFormatter
{
    public HtmlOutputFormatter()
    {
        SupportedMediaTypes.Add("text/html");
    }
}

【讨论】:

  • 感谢您提供详细的方法。 CodeFuller 的答案更短更清晰,这就是我选择他的答案的原因。无论如何+1! ;-)
  • 是的,他的回答很简短,但我的回答很笼统。只需让 Produces 标签工作即可。
猜你喜欢
  • 1970-01-01
  • 2014-06-16
  • 1970-01-01
  • 2016-12-01
  • 1970-01-01
  • 1970-01-01
  • 2014-10-02
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多