Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

return html file from .Net Core api

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

like image 912
Hasan A Yousef Avatar asked Dec 21 '16 06:12

Hasan A Yousef


People also ask

Can we return HTML from API?

To answer the question an API, one that's restful and one that supports json should absolutely be able to return HTML if that's the requested content.

How do I return HTML content in Web API?

Use ControllerBase. The ControllerBase. Content() method returns a ContentResult object. This method has several overloads, and we will be using an overload that accepts two string parameters. The first string represents the content of the HTML while the last is the content-type which for HTML is "text/html" .

Can we return file result from API?

In ASP.NET Core, a Web API action method usually returns an ActionResult object. When we want to return a file response, we can explicitly set the return type for the action method to be FileResult , which is a type inherited from ActionResult .


2 Answers

For .NET Core 2 API you can use this

return Content(html, "text/html", Encoding.UTF8);
like image 90
Cyclion Avatar answered Oct 18 '22 02:10

Cyclion


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;
      });
like image 13
Hasan A Yousef Avatar answered Oct 18 '22 01:10

Hasan A Yousef