Has*_*sef 5 .net .net-core asp.net-core-webapi
我试图用这个和这个得到一个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;
}
}
}
Run Code Online (Sandbox Code Playgroud)
和:
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();
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
我需要将返回的结果作为.html文件,因此我可以使用JavaScript在新的浏览器窗口中打开它var a = window.open(returnedFile, "name");
Cyc*_*ion 18
对于 .NET Core 2 API,您可以使用它
return Content(html, "text/html", Encoding.UTF8);
Run Code Online (Sandbox Code Playgroud)
Has*_*sef 11
感谢@ 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;
}
}
}
Run Code Online (Sandbox Code Playgroud)
为了在浏览器窗口中打开它,我使用了:
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;
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
8218 次 |
| 最近记录: |