ERR_SPDY_PROTOCOL_ERROR when returning file from ASP.NET action

Deadly 提交于 2019-12-24 02:29:07

问题


I have some old Web API action method which returns CSV file. It worked for long time, but recently stopped. Now it causes ERR_SPDY_PROTOCOL_ERROR.

ERR_SPDY_PROTOCOL_ERROR in Chrome is often associated with Avast security as described here. In my case however it's not caused by Avast, and other web browsers throw exceptions too.

My action method looks as follows:

[HttpGet]
[Route("csv")]
public HttpResponseMessage SomeMethod([FromUri]SomeSearchCriteria sc)
{
    using (MemoryStream stream = new MemoryStream())
    {
        StreamWriter writer = new StreamWriter(stream, Encoding.UTF8);
        string content = someLogic.SomeSearchmethod(sc);
        writer.Write(content);
        writer.Flush();
        stream.Position = 0;

        HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK);
        result.Content = new StreamContent(stream);
        result.Content.Headers.ContentType = new MediaTypeHeaderValue("text/csv");
        result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment") { FileName = "Export.csv" };
        return result;
    }              
}

The method is called by angular front end by simple change of window.location on button click.

Whole action method is executed properly, with no exceptions. Error is shown only by web browser.

Flushing sockets in Chrome as described here does not solve the issue.


回答1:


I have tried this method in API controller and call through chrome browser, it throws net::ERR_CONNECTION_RESET

There is some issue in response filled with StreamContent, use ByteArrayContent in result content, it works perfectly.

    [HttpGet]
    [Route("csv")]
    public HttpResponseMessage SomeMethod([FromUri]SomeSearchCriteria sc)
    {
        using (MemoryStream stream = new MemoryStream())
        {
            StreamWriter writer = new StreamWriter(stream, Encoding.UTF8);
            string content = "test";
            writer.Write(content);
            writer.Flush();
            stream.Position = 0;

            HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK);
            //result.Content = new StreamContent(stream);
            result.Content = new ByteArrayContent(stream.ToArray());
            result.Content.Headers.ContentType = new MediaTypeHeaderValue("text/csv");
            result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment") { FileName = "Export.csv" };
            return result;
        }
    }


来源:https://stackoverflow.com/questions/42952906/err-spdy-protocol-error-when-returning-file-from-asp-net-action

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!