вернуть html-файл из .Net Core API

Я пытаюсь использовать это и это, чтобы получить HTML-файл в качестве вывода, но получил error 500

Цель моего приложения основана на запросе API, сервер сгенерирует запрошенный вывод в виде html-файла и отправит его по запросу пользователя.

используются следующие коды:

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

и:

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

Мне нужно, чтобы возвращаемый результат был файлом .html, чтобы я мог открыть его в новом окне браузера, используя JavaScript, например var a = window.open(returnedFile, "name");

введите описание изображения здесь


person Hasan A Yousef    schedule 21.12.2016    source источник
comment
Вы хотите отправить страницу в виде вложения? Если нет, то этот ответ должен помочь вам stackoverflow.com/questions/38105305/   -  person Marcus Höglund    schedule 21.12.2016
comment
@MarcusH Я проверю это завтра, но похоже, что это будет отображаться непосредственно в браузере, мне нужно, чтобы пользователь получил file, чтобы с помощью JavaScript я мог открыть его в другом окне, отличном от открытого, например var a = window.open(url, "name");   -  person Hasan A Yousef    schedule 21.12.2016
comment
Необходим стриминг?   -  person J. Doe    schedule 21.12.2016
comment
@ J. Не уверен, я только что нашел это в другом решении, близком к моему делу.   -  person Hasan A Yousef    schedule 22.12.2016


Ответы (3)


Для .NET Core 2 API вы можете использовать это

return Content(html, "text/html", Encoding.UTF8);
person Cyclion    schedule 06.08.2018

Спасибо за отзыв и ответ @Marcus-h, я решил проблему, используя [Produces("text/html")] и получив возврат как string, поэтому полный код:

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

Чтобы открыть его в окне браузера, я использовал:

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;
      });
person Hasan A Yousef    schedule 22.12.2016
comment
Хорошее решение! Атрибут «Производит» был для меня новым, проверю. - person Marcus Höglund; 22.12.2016
comment
Он работает на .Net core 1.0, но не на 2.0, вам нужно вручную добавить средство форматирования вывода для текста/html, см.: github.com/aspnet/Mvc/issues/6657 - person Akli; 12.09.2017

Чтобы вернуть html-страницу через API, вы можете использовать HttpResponseMessage и установить тип содержимого «text/html». Проблема в том, что ядро ​​.net по умолчанию не поддерживает ответ HttpResponseMessage.

Шаг 1

Чтобы включить тип ответа из методов веб-API, выполните шаги из отличный ответ Свика.

Шаг 2

Примените следующий метод к контроллеру

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

Шаг 3

Вызов API непосредственно в методе window.open, который по умолчанию откроется в новом окне (_blank)

window.open('http://localhost:2222/api/file')
person Marcus Höglund    schedule 21.12.2016
comment
Строка ответа не появилась, вместо этого я получил вывод как: {"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} - person Hasan A Yousef; 22.12.2016
comment
@HasanAYousef Я обновил свой ответ. У меня не было проблем с получением ожидаемого результата. Вы передаете URL-адрес непосредственно в методе window.open, как показано в примере? - person Marcus Höglund; 22.12.2016
comment
У меня то же самое, но результаты, о которых я вам говорил. - person Hasan A Yousef; 22.12.2016
comment
@HasanAYousef Обновил мой ответ - person Marcus Höglund; 22.12.2016
comment
Я добавил "Microsoft.AspNetCore.Mvc.WebApiCompatShim":"1.1.0" к своему project.json, но получил эту ошибку: Package Microsoft.AspNet.WebApi.Client 5.2.2 is not compatible with netcoreapp1.1 (.NETCoreApp,Version=v1.1) я использовал все остальные version числа, все еще получая ту же ошибку. - person Hasan A Yousef; 22.12.2016