[英]HttpContext.Response.WriteAsync("<h1>hello world</h1>") onGet handler method throw Exception in asp.net core 6 webapp
HttpContext.Response.WriteAsync(<h1>hello world</h1>") onGet handler method throws Exception in asp.net core 6 webapp
HttpContext.Response.WriteAsync("<h1>hello world</h1>")
Code Details
-------------
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
namespace ResponserWrite.Pages
{
public class IndexModel : PageModel
{
private readonly ILogger<IndexModel> _logger;
public IndexModel(ILogger<IndexModel> logger)
{
_logger = logger;
}
public void OnGet()
{
HttpContext.Response.WriteAsync("<h1>hello world</h1>");
}
}
}
fail: Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware[1] An unhandled exception has occurred while executing the request.失败:Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware[1] 执行请求时发生未处理的异常。 System.InvalidOperationException: Headers are read-only, response has already started.
System.InvalidOperationException:标头是只读的,响应已经开始。
It seems that you have a misconception how Razor pages app works.您似乎误解了Razor 页应用程序的工作原理。 The actual response is generated by the framework using your model (
Something.cshtml.cs
) and the "view"/"page" ( Something.cshtml
).实际响应是由框架使用您的 model (
Something.cshtml.cs
) 和“视图”/“页面”( Something.cshtml
) 生成的。 In the model in corresponding methods you need to load/manage the required data and in the page file you change it's representation via modifying output html.在 model 的相应方法中,您需要加载/管理所需的数据,并在页面文件中通过修改 output html 来更改其表示。
In case if you try to write the response manually it will cause the aforementioned exception when the framework will try to start the response too.如果您尝试手动编写响应,当框架也尝试启动响应时,会导致上述异常。
If you want to add some html to index page - just open Index.cshtml
and add it somewhere.如果您想将一些 html 添加到索引页面 - 只需打开
Index.cshtml
并将其添加到某处。
Read more:阅读更多:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.