ASP.NET MVC:如何在返回FileResult时设置编码 [英] ASP.NET MVC: how to set encoding when returning FileResult

查看:407
本文介绍了ASP.NET MVC:如何在返回FileResult时设置编码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的控制器中,我具有以下将存储在CSHTML文件中的HTML代码段发送到前端的功能.

In my controller, I have the following to send HTML snippet stored in CSHTML files to the front.

    public FileResult htmlSnippet(string fileName)
    {
        string contentType = "text/html";
        return new FilePathResult(fileName, contentType);
    }

fileName如下所示:

The fileName looks like the following:

/file/abc.cshtml

/file/abc.cshtml

现在让我困扰的是这些HTML代码段文件包含西班牙语字符,当它们显示在页面中时看起来不正确.

What troubles me now is that these HTML snippet files have Spanish characters and they don't look right when they are displayed in pages.

感谢和问候.

推荐答案

首先请确保您的文件采用UTF-8编码:

检查讨论.

如何设置响应的编码:

我认为您可以这样做:

 public FileResult htmlSnippet(string fileName)
    {
        string contentType = "text/html";
        var fileResult = new FilePathResult(fileName, contentType);
        Response.Charset = "utf-8"; // or other encoding
        return fileResult;
    }

其他选项是创建过滤器属性,然后您可以使用该属性标记单独的控制器或动作(或将其添加到全局过滤器中):

Other option is to create Filter attribute, then you can mark separate controllers or actions with this attribute (or add it to global filters):

public class CharsetAttribute : ActionFilterAttribute
{
    public override void OnActionExecuted(ActionExecutedContext filterContext)
    {
        filterContext.HttpContext.Response.Headers["Content-Type"] += ";charset=utf-8";
    }
}

如果您想为所有HTTP响应设置编码,则也可以尝试在web.config中设置编码.

If you wanna to set encoding for all HTTP responses you may try to set encoding in web.config as well.

<configuration>
  <system.web>
    <globalization requestEncoding="utf-8" responseEncoding="utf-8" />
  </system.web>
</configuration>

这篇关于ASP.NET MVC:如何在返回FileResult时设置编码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆