ASP.NET Core API控制器通常返回显式类型(默认情况下,如果您创建一个新项目),如下所示:
[Route("api/[controller]")]
public class ThingsController : Controller
{
// GET api/things
[HttpGet]
public async Task<IEnumerable<Thing>> GetAsync()
{
//...
}
// GET api/things/5
[HttpGet("{id}")]
public async Task<Thing> GetAsync(int id)
{
Thing thingFromDB = await GetThingFromDBAsync();
if(thingFromDB == null)
return null; // This returns HTTP 204
// Process thingFromDB, blah blah blah
return thing;
}
// POST api/things
[HttpPost]
public void Post([FromBody]Thing thing)
{
//..
}
//... and so on...
}
Run Code Online (Sandbox Code Playgroud)
问题是return null;- 它返回HTTP 204:成功,没有内容.
然后,许多客户端Javascript组件将其视为成功,因此代码如下:
const …Run Code Online (Sandbox Code Playgroud) c# http-status-code-404 asp.net-core-mvc asp.net-core asp.net-core-webapi
对于HTTP 500代码,Microsoft.AspNetCore.Mvc.Controller基类没有等效的BadRequest(),Ok(),NoContent()等。
我们为什么不能做一个
try{
oops();
}
catch(Excpetion e){
//some handling
return InternalServerError(e);
}
Run Code Online (Sandbox Code Playgroud)
我知道可以返回StatusCode(500);
但是我们正在尝试与我们的HTTP代码更加一致,并且想知道对于500个代码,是否存在与Ok()更一致的东西。
我们有一个控制器,它派生自这样ControllerBase的动作:
public async Task<ActionResult> Get(int id)
{
try
{
// Logic
return Ok(someReturnValue);
}
catch
{
return Problem();
}
}
Run Code Online (Sandbox Code Playgroud)
我们还有这样的单元测试:
[TestMethod]
public async Task GetCallsProblemOnInvalidId()
{
var result = sut.Get(someInvalidId);
}
Run Code Online (Sandbox Code Playgroud)
但是ControllerBase.Problem()抛出一个空引用异常。这是来自 Core MVC 框架的一个方法,所以我真的不知道它为什么会抛出错误。我认为可能是因为 HttpContext 为空,但我不确定。是否有一种标准化的方法来测试控制器应该调用的测试用例Problem()?任何帮助表示赞赏。如果答案涉及模拟:我们使用 Moq 和 AutoFixtrue。