【问题标题】:Set Response Status code in View Component在视图组件中设置响应状态码
【发布时间】:2020-06-12 14:43:35
【问题描述】:

我想在视图组件中设置状态码,以便我可以在 .ts 文件中检查。

这是我的 .ts 文件代码

window.onload = function () {

    fetch('../Controller/ActionName',
        {
            headers: {
                RequestVerificationToken: (<HTMLInputElement>document.getElementById("Token")).value
            }
        })
        .then((response) => {
            if (response.status != 200) {
                redirectToHomePage();
            }
            response.text().then((data) => {
                document.getElementById("Id")!.innerHTML = data;
            });
        });

    // Redirect to home page
    function redirectToHomePage() {
        var url = window.location.origin;
        window.location.href = url + '/Login/Login/';
    }
};

Action 将调用 ViewComponent 并返回响应 然后我想检查视图组件中是否没有错误,那么它将是 200 如果视图组件有错误,那么它将是任何其他错误代码。

下面是 ViewComponent 代码

protected IViewComponentResult TestViewComponent()
{
    try
    {
        // Do code here
    }
    Catch(Exception ex){                
        return View(viewName)
    }

    return View(viewName);
}

我想在 catch 块中设置状态码。

请帮帮我。

提前谢谢你。

【问题讨论】:

    标签: asp.net-core


    【解决方案1】:

    不能作为 HTTP 端点直接访问。它们被调用 您的代码(通常在视图中)。视图组件从不处理 请求。

    根据doc,组件从不处理请求,视图组件方法在签名上重载,而不是来自当前 HTTP 请求的任何细节。所以你不能直接返回视图组件内的状态码。如果你想在视图组件中返回自定义状态码是不可能的。

    您应该修改代码以将检查逻辑移动到控制器操作中,而不是像下面这样的视图组件:

    public IActionResult LoadVisit(int? id)
    {
    
        if (id == null || id == 0)
        {
            return NotFound();
        }
        var model = new VisitViewModel();
        try
        {
            model = await visitAPI.GetVisit(clientID, visitID);
        }
        catch (Exception ex)
        {
            return StatusCode(500, "Error message");
        }
    
        return ViewComponent("ClientVisit", model });
    
    }
    

    但是如果你直接在视图组件内部抛出异常,客户端会收到 500 错误而不是 200。

    如下测试演示:

    public class PriorityListViewComponent : ViewComponent
    {
        private readonly ToDoContext db;
    
        public PriorityListViewComponent(ToDoContext context)
        {
            db = context;
        }
    
        private Task<List<TodoItem>> GetItemsAsync(int maxPriority, bool isDone)
        {
            return db.ToDo.Where(x => x.IsDone == isDone &&
                                 x.Priority <= maxPriority).ToListAsync();
        }
        #region snippet1
        public async Task<IViewComponentResult> InvokeAsync(
            int maxPriority, bool isDone)
        {
            string MyView = "Default";
            // If asking for all completed tasks, render with the "PVC" view.
            if (maxPriority > 3 && isDone == true)
            {
                MyView = "PVC";
            }
            try
            {
                var items = await GetItemsAsync(maxPriority, isDone);
                return View(MyView, items);
            }
            catch (Exception)
            {
                throw;
            }
    
        }
        #endregion
    }
    

    【讨论】:

    • 因为返回类型是 IViewComponentResult 所以不能使用 return StatusCode(500);
    • 据我所知,组件从不处理请求,视图组件方法在签名上重载,而不是来自当前 HTTP 请求的任何细节。因此,您应该将检查逻辑移出视图组件并进入控制器,然后在没有异常的情况下将结果数据传递到视图组件。请参阅我的更新方法。我们将在控制器操作中调用 ViewComponent。
    • 另外,如果直接在ViewComponent代码中抛出错误,客户端会收到500错误。
    猜你喜欢
    • 2020-04-20
    • 2011-09-04
    • 2021-07-21
    • 2021-04-28
    • 1970-01-01
    • 2021-04-24
    • 2016-09-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多