我如何使用 AspNetCore 抛出 HttpResponseException(NotFound)

sim*_*ada 0 .net c# asp.net-core

我写的方法.Net 4.5 很简单。它要么returns Student entity or throw NOT FOUND exception.

我正在努力port it into .NET Core 2.0. 根据我的理解,.net core建议返回IActionResult,我可以简单地返回NotFound().

但是,我不确定如何抛出 not HttpResponseException (Not Found) 异常。

方法:

public Student Get(Guid id)
{
    Student student = _studentSvc.Get(id);
    if (student != null)
        return student;
    else
        throw new HttpResponseException(HttpStatusCode.NotFound);
}
Run Code Online (Sandbox Code Playgroud)

试图:

public Student Get(Guid id)
{
    Student student = _svc.Get(id);
    if (student != null)
        return student;
    else
        return NotFound();
}
Run Code Online (Sandbox Code Playgroud)

如果我尝试跟随,那么这条线会return student抱怨不能隐式地将学生转换为...Mvc.IActionResult某些东西

public IActionResult Get(Guid id)
{
    Student student = _svc.Get(id);
    if (student != null)
        return student;
    else
        return NotFound();
}
Run Code Online (Sandbox Code Playgroud)

但它给出了错误无法将 NotFoundResult 转换为 Student !!

Kiw*_*iet 5

正如您所提到的,您需要返回 IActionResult 。

public IActionResult Get(Guid id)
{
    Student student = _svc.Get(id);
    if (student != null)
    {
        return Ok(student);
    }
    return NotFound();
}
Run Code Online (Sandbox Code Playgroud)