简体   繁体   English

ActionFilter响应类型(text / html)与响应内容不匹配

[英]ActionFilter response type (text/html) does not match the response content

Using: C#, MVC 5, IIS 8 使用:C#,MVC 5,IIS 8

I am trying to implement an ActionFilter that will minify html. 我正在尝试实现一个将缩小html的ActionFilter。 The basic approach here is to substitute the response's Stream with a custom Stream that writes input into a MemoryStream and then on the Close method minifies the content stored in the MemoryStream and writes out the (minified) content. 这里的基本方法是将响应的Stream替换为将输入写入MemoryStream的自定义Stream,然后使用Close方法缩小存储在MemoryStream中的内容并写出(缩小的)内容。

The problem I am having is that although the response's type is 'text/html', the content passed to the custom Stream does not look like text or html, it looks like binary. 我遇到的问题是,虽然响应的类型是“text / html的”,传递到自定义内容流并不像文本或HTML,它看起来像二进制。 I should add that my site's pages are rendering just fine, so whatever that content is, it's not complete garbage. 我应该补充一点,我的网站的页面渲染得很好,所以无论内容是什么,它都不是完全垃圾。 I added some logging statements to debug, and this is what they look like: 我添加了一些日志语句来调试,这就是它们的样子:

Minification Error | 缩小错误| Chunks: 1 | 大块:1 | Url: /Login/iFrameLogin.aspx | 网址:/Login/iFrameLogin.aspx | Encoding: System.Text.UTF8Encoding | 编码:System.Text.UTF8Encoding | MediaType: text/html | MediaType:text / html | Content: 内容:

I have also tried turning off dynamic compression on my site, and that made no change either. 我也尝试在我的网站上关闭动态压缩,这也没有改变。 Does anyone have any ideas why my 'text/html' looks like binary? 有没有人有任何想法为什么我的'text / html'看起来像二进制?

FilterAttribute FilterAttribute

public class MinifyHtmlFilterAttribute : ActionFilterAttribute
{
    public override void OnResultExecuted(ResultExecutedContext filterContext)
    {
        HttpContextBase context = filterContext.HttpContext;
        HttpRequestBase request = context.Request;
        HttpResponseBase response = context.Response;
        Encoding encoding = response.ContentEncoding;
        string mediaType = response.ContentType;
        string currentUrl = request.RawUrl;
        var minificationManager = HtmlMinificationManager.Current;

        if (response.Filter != null
            && response.StatusCode == 200
            && minificationManager.IsSupportedMediaType(mediaType) //text/html
            && minificationManager.IsProcessablePage(currentUrl))
        {
            response.Filter = new HtmlMinificationFilterStream(response, minificationManager, currentUrl, encoding, mediaType);
        }
    }
}

Custom Stream 自定义流

public class HtmlMinificationFilterStream : Stream
{
    private readonly HttpResponseBase _response;
    private readonly Stream _stream;
    private readonly MemoryStream _cacheStream = new MemoryStream();

    private readonly IMarkupMinificationManager _minificationManager;

    private readonly string _currentUrl;
    private readonly Encoding _encoding;
    private readonly string _mediaType;
    private int _chunkCount = 0;

    public override bool CanRead
    {
        get { return true; }
    }

    public override bool CanSeek
    {
        get { return true; }
    }

    public override bool CanWrite
    {
        get { return true; }
    }

    public override long Length
    {
        get { return 0; }
    }

    public override long Position
    {
        get;
        set;
    }

    public HtmlMinificationFilterStream(HttpResponseBase response,
        IMarkupMinificationManager minificationManager,
        string currentUrl,
        Encoding encoding,
        string mediaType)
    {
        _response = response;
        _stream = response.Filter;
        _minificationManager = minificationManager;
        _currentUrl = currentUrl;
        _encoding = encoding;
        _mediaType = mediaType;
    }

    public override int Read(byte[] buffer, int offset, int count)
    {
        return _stream.Read(buffer, offset, count);
    }

    public override long Seek(long offset, SeekOrigin origin)
    {
        return _stream.Seek(offset, origin);
    }

    public override void SetLength(long value)
    {
        _stream.SetLength(value);
    }

    public override void Write(byte[] buffer, int offset, int count)
    {
        _cacheStream.Write(buffer, 0, count);
        _chunkCount++;
    }

    public override void Flush()
    {
        _stream.Flush();
    }

    public override void Close()
    {
        byte[] cacheBytes = _cacheStream.ToArray();
        int cacheSize = cacheBytes.Length;
        string content = _encoding.GetString(cacheBytes);
        var log = $" | Chunks: {_chunkCount} | Url: {_currentUrl} | Encoding: {_encoding} | MediaType: {_mediaType} | Content: {content}";

        IMarkupMinifier minifier = _minificationManager.CreateMinifier();
        MarkupMinificationResult minificationResult = minifier.Minify(content, _currentUrl, _encoding, false);
        bool isMinified = false;
        if (minificationResult.Errors.Count == 0)
        {
            ExceptionHandler.LogException("MINIFICATION SUCCESS" + log, System.Diagnostics.EventLogEntryType.Warning);
            using (var writer = new StreamWriter(_stream, _encoding))
            {
                writer.Write(minificationResult.MinifiedContent);
            }

            isMinified = true;
        }
        else
        {
            foreach (var error in minificationResult.Errors)
            {
                ExceptionHandler.LogException("Minification Error" + log + " | " + error.SourceFragment, System.Diagnostics.EventLogEntryType.Warning);
            }
        }

        if (!isMinified)
        {
            _cacheStream.Seek(0, SeekOrigin.Begin);
            _cacheStream.CopyTo(_stream);
        }

        _cacheStream.SetLength(0);
        _stream.Close();
    }
}

关闭IIS上的压缩(8)可以解决问题。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 网络服务错误:响应消息的内容类型text / html与绑定的内容类型不匹配 - webservice error: The content type text/html of the response message does not match the content type of the binding 内容类型text / html; charset =响应消息的UTF-8与绑定的内容类型不匹配(text / xml; charset = utf-8) - The content type text/html; charset=UTF-8 of the response message does not match the content type of the binding (text/xml; charset=utf-8) wcf +响应消息的内容类型text / html与绑定的内容类型不匹配(application / soap + xml; charset = utf-8) - wcf + The content type text/html of the response message does not match the content type of the binding (application/soap+xml; charset=utf-8) WCF 服务客户端:内容类型text/html; 响应消息的 charset=utf-8 与绑定的内容类型不匹配 - WCF Service Client: The content type text/html; charset=utf-8 of the response message does not match the content type of the binding C#ASMX服务抛出内容类型text / html; charset =响应消息的UTF-8与内容类型错误不匹配 - C# ASMX Service throwing The content type text/html; charset=UTF-8 of the response message does not match the content type error 响应消息的内容类型文本/纯文本与绑定的内容类型不匹配(文本/ xml; charset = utf-8) - The content type text/plain of the response message does not match the content type of the binding (text/xml; charset=utf-8) 内容类型 text/xml; 响应消息的 charset="utf-8" 与绑定的内容类型不匹配 (text/xml; charset=utf-8) - The content type text/xml; charset=“utf-8” of the response message does not match the content type of the binding (text/xml; charset=utf-8) 响应消息的内容类型application / xml; charset = utf-8与绑定的内容类型不匹配(text / xml; charset = utf-8) - The content type application/xml;charset=utf-8 of the response message does not match the content type of the binding (text/xml; charset=utf-8) 响应消息的内容类型 application/xml;charset=utf-8 与绑定的内容类型(text/xml; charset=utf-8)不匹配,WCF - The content type application/xml;charset=utf-8 of the response message does not match the content type of the binding (text/xml; charset=utf-8), WCF 客户发现响应内容类型为“text / html”,但预期为“text / xml” - Client found response content type of 'text/html', but expected 'text/xml'
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM