我的方法是用.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 !!
答案 0 :(得分:2)
如您所述,您需要返回IActionResult。
public IActionResult Get(Guid id)
{
Student student = _svc.Get(id);
if (student != null)
{
return Ok(student);
}
return NotFound();
}