7

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

4
  • Do you want to send the page as an attachement? If not then this answer should help you stackoverflow.com/questions/38105305/… Commented Dec 21, 2016 at 6:16
  • @MarcusH I'll test it tomorrow, but it looks this will be displayed directly in the browser, I need the user to receive a file so using JavaScript i can open it in another window other than the opened one like var a = window.open(url, "name"); Commented Dec 21, 2016 at 11:30
  • Streaming is necessary? Commented Dec 21, 2016 at 11:41
  • @J.Doe not sure, I just found this in another solution near to my case Commented Dec 22, 2016 at 5:47

3 Answers 3

22

For .NET Core 2 API you can use this

return Content(html, "text/html", Encoding.UTF8);
Sign up to request clarification or add additional context in comments.

Comments

13

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;
      });

2 Comments

Nice solution! The Produces attribute was new to me, will check that out.
It works on .Net core 1.0 but not on 2.0, you need to manually add an output formatter for the "text/html", see : github.com/aspnet/Mvc/issues/6657
1

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')

5 Comments

The responseString did not appear, instead I got the output as: {"version":{"major":1,"minor":1,"build":-1,"revision":-1,"majorRevision":-1,"minorRevision":-1},"content":{"headers":[{"key":"Content-Type","value":["text/html"]}]},"statusCode":200,"reasonPhrase":"OK","headers":[],"requestMessage":null,"isSuccessStatusCode":true}
@HasanAYousef I've updated my answer. I had no trouble getting the expected result. Do you pass the url directly in the window.open method as I show in the example?
I've it same we, but got the results I told you about.
@HasanAYousef Updated my answer
I added the "Microsoft.AspNetCore.Mvc.WebApiCompatShim":"1.1.0" to my project.json but got this error: Package Microsoft.AspNet.WebApi.Client 5.2.2 is not compatible with netcoreapp1.1 (.NETCoreApp,Version=v1.1) i used all other version numbers, still getting the same error.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.