return html file from .Net Core api

27.6k views Asked by At

I'm trying to use this and this to get an html file as output, but got error 500

The objective of my app is based on the api request, the server will generate the requested output as html file, and send it to the user request.

the codes used are:

using Microsoft.AspNetCore.Mvc;  // for Controller, [Route], [HttpPost], [FromBody], JsonResult and Json
using System.IO;   // for MemoryStream
using System.Net.Http; // for HttpResponseMessage
using System.Net;  // for HttpStatusCode
using System.Net.Http.Headers;  // for MediaTypeHeaderValue

namespace server{
    [Route("api/[controller]")]
    public class FileController : Controller{
    [HttpGet]
    public HttpResponseMessage Get()
    {
        string r = @" 
            Hello There
        ";
        var stream = new MemoryStream();
        StreamWriter writer = new StreamWriter(stream);
        writer.Write(r);
        writer.Flush();
        stream.Position = 0;

       // processing the stream.
       byte[] Content = convert.StreamToByteArray(stream);
       var result = new HttpResponseMessage(HttpStatusCode.OK);


        result.Content.Headers.ContentDisposition =
            new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment")
        {
            FileName = "welcome.html"
        };
        result.Content.Headers.ContentType =
            new MediaTypeHeaderValue("application/octet-stream");

        return result;
    }
  }
}

and:

using System.IO;  // for MemoryStream

namespace server{
    class convert{
            public static byte[] StreamToByteArray(Stream inputStream)
            {
                byte[] bytes = new byte[16384];
                using (MemoryStream memoryStream = new MemoryStream())
                {
                    int count;
                    while ((count = inputStream.Read(bytes, 0, bytes.Length)) > 0)
                    {
                        memoryStream.Write(bytes, 0, count);
                    }
                    return memoryStream.ToArray();
                }
            }
    }
}

I need the returned result to be a .html file, so I can open it in a new browser window using JavaScript like var a = window.open(returnedFile, "name");

enter image description here

3

There are 3 answers

2
Hasan A Yousef On BEST ANSWER

Thanks for @Marcus-h feedback and answer, I got it solved by using [Produces("text/html")] and having the return as string, so the full code is:

namespace server{
    [Route("api/[controller]")]
    public class FileController : Controller{
        [HttpGet]
        [Produces("text/html")]
        public string Get()
        {
            string responseString = @" 
            <title>My report</title>
            <style type='text/css'>
            button{
                color: green;
            }
            </style>
            <h1> Header </h1>
            <p>Hello There <button>click me</button></p>
            <p style='color:blue;'>I am blue</p>
            ";
            return responseString;
        }
    }
}

To get it opened in a browser window, i used:

var report = window.open('', 'myReport', 'location=no,toolbar=0');
// or var report = window.open(''); // if I need the user to be able to use the browser actions, like history
report.document.title = 'My report';  // if title not added in the server code
fetch('http://localhost:60000/api/File', {
       method: 'get'
      })
      .then(function(response) {
            return response.text();
      }).then(function(text) { 
            report.document.body.innerHTML = text;
      });
5
Marcus Höglund On

To return a html page via the api you could use HttpResponseMessage and set the content type to "text/html". The problem is that .net core dosen't support the HttpResponseMessage response by default.

Step 1

To enable the response type from the web api methods, please follow the steps from svicks great answer.

Step 2

Apply the following method to the controller

[HttpGet]
public HttpResponseMessage Get()
{
    string responseString = @" 
        Hello There
    ";
    var response = new HttpResponseMessage();
    response.Content =  new StringContent(responseString);
    response.Content.Headers.ContentType = new MediaTypeHeaderValue("text/html");
    return response;
}

Step 3

Call the api directly in the window.open method which by default will open itself in a new window(_blank)

window.open('http://localhost:2222/api/file')
0
Cyclion On

For .NET Core 2 API you can use this

return Content(html, "text/html", Encoding.UTF8);