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

时间:2017-08-18 02:35:13

标签: c# .net 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().

  

但是,我不知道如何抛出非HttpResponseException(Not Found)异常。

方法:

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

尝试:

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

如果我尝试跟随,那么此行return student抱怨无法隐式将学生转换为...Mvc.IActionResult某事

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

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

1 个答案:

答案 0 :(得分:2)

如您所述,您需要返回IActionResult。

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