尝试在ActionResult中返回HTML会导致HTTP 406错误

Raz*_*zor 3 c# asp.net-mvc iframe asp.net-core-mvc

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

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

这显示没有任何内容<iframe>.我试过了:

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

Microsoft Edge向我提供以下消息:

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

Firefox和Chrome拒绝显示任何内容.我也试过HtmlEncode了正常ActionResult.以下是<iframe>我视图中的片段:

<div class="row">
    <div class="col-sm-12">
        <iframe src="/Home/DisplayWebPage" class="col-sm-12"></iframe>
    </div>
</div>
Run Code Online (Sandbox Code Playgroud)

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

Pra*_*dey 7

有两种方法可以执行此操作: 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",
    };
}
Run Code Online (Sandbox Code Playgroud)

2.更新行动:

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

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

services.AddMvc(options => options.OutputFormatters.Add(new HtmlOutputFormatter()));
Run Code Online (Sandbox Code Playgroud)

其中HtmlOutputFormatter是:

public class HtmlOutputFormatter : StringOutputFormatter
{
    public HtmlOutputFormatter()
    {
        SupportedMediaTypes.Add("text/html");
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 是的,他的回答很简短,但我的回答很一般。只需让 Produces 标签工作。 (2认同)

Cod*_*ler 6

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

另一个选项是将操作的返回类型更改为通过标头string请求text/html格式Accept.有关详细信息,请参阅格式化响应简介.