首页 新闻 会员 周边

ASP.NET Core: 如何在 ViewComponent 中返回 404 响应

0
悬赏园豆:30 [待解决问题]

想在 ViewComponent 中直接返回 404,但 return new NotFoundResult(); 会提示错误

Cannot implicitly convert type 'Microsoft.AspNetCore.Mvc.NotFoundResult' to 'Microsoft.AspNetCore.Mvc.IViewComponentResult'.
问题补充:
  • 使用 HttpContext.Response.OnStarting 不可行:

更新:Response.OnStarting 可以修改状态码,但无法阻止响应内容的输出。

HttpContext.Response.OnStarting(
state =>
{
    var context = (HttpContext)state;
    context.Response.StatusCode = 404;
    return Task.CompletedTask;
},
HttpContext);

return new ContentViewComponentResult(string.Empty);
  • 自己实现 StatusCodeViewComponentResult 也不可行:
return new StatusCodeViewComponentResult(404);
public class StatusCodeViewComponentResult : IViewComponentResult
{
    private readonly int _statusCode;

    public StatusCodeViewComponentResult(int statusCode)
    {
        _statusCode = statusCode;
    }

    public void Execute(ViewComponentContext context)
    {
        context.ViewContext.HttpContext.Response.StatusCode = _statusCode;
    }

    public Task ExecuteAsync(ViewComponentContext context)
    {
        context.ViewContext.HttpContext.Response.StatusCode = _statusCode;
        return Task.CompletedTask;
    }
}
dudu的主页 dudu | 高人七级 | 园豆:31003
提问于:2023-03-08 11:09
< >
分享
所有回答(1)
0

在 ViewComponent 中返回 404 可以尝试使用 ContentResult,它是 IActionResult 的实现类,可以返回一个字符串作为响应内容。在这个字符串中可以包含自定义的错误信息,例如 "404 Not Found"。您可以按以下方式在 ViewComponent 中返回 404:

csharp

return new ContentResult
{
StatusCode = 404,
ContentType = "text/plain",
Content = "404 Not Found"
};
请注意,在上面的代码示例中,ContentType 的值是 "text/plain",这表明响应内容的类型是纯文本。如果您希望响应内容的类型为 HTML,则可以将 ContentType 设置为 "text/html"。

Technologyforgood | 园豆:5575 (大侠五级) | 2023-03-28 21:50
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册