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");
Thanks for @Marcus-h feedback and answer, I got it solved by using
[Produces("text/html")]
and having the return asstring
, so the full code is:To get it opened in a browser window, i used: