1

this is my first time to ask question here in stackoverflow and I know this question is already asked by others but mine is different because I already did what other question like this was advise but still got the same error.

Here is my code in my APIController:

    [HttpGet]
    [Route("GenerateReport")]
    public IHttpActionResult GenerateReport()
    {
        try
        {
            byte[] bytes = Generate();

            System.Web.HttpResponse response = System.Web.HttpContext.Current.Response;

            response.Clear();
            response.ClearHeaders();
            response.BufferOutput = true;
            response.AppendHeader("Content-Type", "application/pdf");
            response.AppendHeader("Content-Disposition", "attachment;filename=test.pdf;");
            //response.Flush();
            response.BinaryWrite(bytes.ToArray());
            response.End();

            //HttpContext.Current.ApplicationInstance.CompleteRequest();

            return Ok(response);
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }

it successfully download the file but still error since we have an existing code that redirect the application to an Error.aspx and from there the error will display.

    void application_Error(object sender, EventArgs e)
    {
        HttpApplication application = (HttpApplication)sender;
        var exception = application.Server.GetLastError();
        if (exception is HttpException)
        {
            HttpException httpEx = (HttpException)exception;
            if (httpEx.GetHttpCode() == 404)
            {
                //application.Server.ClearError();
                //HttpContext.Current.Response.TrySkipIisCustomErrors = true;
                HttpContext.Current.Response.StatusCode = 404;
                //Trace.WriteLine("404 for " + HttpContext.Current.Request.Url);
                //throw new ApplicationException("fadsasdfasdfasdfasf");
                //HttpContext.Current.Server.Transfer("~/Four04.ashx");
                return;
            }
        }
        if (exception is ThreadAbortException)
        {
            if (exception.StackTrace.Contains("System.Web.HttpResponse.Redirect(String url, Boolean endResponse, Boolean permanent)"))
            {
                // ThreadAbortException following a Response.Redirect()
                // Do not bother, it is native
                return;
            }
        }

        LogException(exception.GetExplicitBaseException(),  application.Context);
                       application.Server.Transfer(CoreWebApplication.Current.ErrorPageUrl);

    }
g0y
  • 73
  • 1
  • 14

1 Answers1

1

You can use the following code in order to set a proper response. I believe you get your error because you are modifying the HttpContext response (however, do not quote me on that).

[HttpGet]
[Route("GenerateReport")]
public HttpResponseMessage GenerateReport()
{
    byte[] bytes = Generate();

    HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK);
    var stream = new MemoryStream(bytes);
    result.Content = new StreamContent(stream);
    result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/pdf");
    result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
    {
        FileName = "test.pdf"
    };

    return result;
}

Thanks to:Returning binary file from controller in ASP.NET Web API

Community
  • 1
  • 1
StfBln
  • 1,137
  • 6
  • 11