如何从Asp.Net Core View组件返回错误的HTTP状态代码 [英] How to return HTTP Status Codes for errors from Asp.Net Core View Component

查看:72
本文介绍了如何从Asp.Net Core View组件返回错误的HTTP状态代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图从Asp.Net Core中的View组件返回HTTP 500或BadRequest()结果,但是此返回类型似乎不适用于View组件.状态代码返回类型应该可用于View组件还是我的设计有误?

I am trying to return a HTTP 500 or BadRequest() result from my View Component in Asp.Net Core however this return type does not appear to be available for View Components. Should status code return types be available for View Components or have i got my design wrong?

我正在按照以下方式通过ajax调用我的控制器动作...

I am calling my controller action via ajax as per below...

<a asp-controller="Client" asp-action="LoadVisit" asp-route-id="@item.VisitID" data-ajax="true" data-ajax-method="GET" data-ajax-update="#ClientVisit" data-ajax-mode="replace" data-ajax-failure="AjaxOnFailure(xhr, status, error)" role="button"><i class="fa fa-folder-open-o"></i></a>

我的控制器操作正在按如下所述调用/返回我的View组件...

My controller action is calling/returning my View Component as per below...

public IActionResult LoadVisit(int? id)
{

    if (id == null || id == 0)
    {
        return NotFound();
    }

    return ViewComponent("ClientVisit", new { visitID = id.GetValueOrDefault() });

}

我的ClientVisit视图组件具有以下内容...

My ClientVisit View Component has the following...

public async Task<IViewComponentResult> InvokeAsync(int? clientID, int? visitID)
{

    try
    {
        var model = new VisitViewModel();
        model = await visitAPI.GetVisit(clientID, visitID);
        return View(model);
    }
    catch (Exception ex)
    {
        return Content(ex.Message);
    }

}

当我的数据库调用 model = await visitAPI.GetVisit(clientID,visitID)失败时,我想返回 return StatusCode(500,ex.ToString()),但是无法使用,因此我的ajax调用认为我的请求成功了,这是错误的.

When my database call model = await visitAPI.GetVisit(clientID, visitID) fails I want to return return StatusCode(500, ex.ToString()) but it's not available so my ajax call thinks my request was successful which is wrong.

推荐答案

只要您具有HttpResponse的访问权限,它就应该起作用.或者,由于ViewComponent先决条件检查的返回,然后设置状态.

As long as you have the HttpResponse in the access it should work. Alternatively, due to the return of the ViewComponent prerequisite check then set the status.

try
{
    var model = new VisitViewModel();
    model = await visitAPI.GetVisit(clientID, visitID);
    return View(model);
}
catch (Exception ex)
{
     Response.StatusCode = (int)HttpStatusCode.BadRequest;
     return null;
}

这篇关于如何从Asp.Net Core View组件返回错误的HTTP状态代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆