gpt4 book ai didi

.net - 从.Net Core api返回html文件

转载 作者:行者123 更新时间:2023-12-02 20:03:56 25 4
gpt4 key购买 nike

我正在尝试使用 thisthis获取 html 文件作为输出,但得到错误 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");

enter image description here

最佳答案

对于 .NET Core 2 API,您可以使用此

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

关于.net - 从.Net Core api返回html文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41256268/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com