如果出现问题,如何从ASP.NET Core 1.0中的API方法返回HttpStatus代码?
如果该方法应该返回一个特定的对象类型,当我尝试返回一个Http状态代码时,我收到一条错误,说我无法将我的对象转换为状态代码。
[HttpPost]
public async Task<SomeObject> Post([FromBody] inputData)
{
// I detect an error and want to return BadRequest HttpStatus
if(inputData == null)
return new HttpStatusCode(400);
// All is well, so return the object
return myObject;
}
答案 0 :(得分:11)
从控制器操作返回IActionResult
:
public async Task<IActionResult> Post([FromBody] InputData inputData)
{
if(inputData == null)
{
return new HttpStatusCodeResult((int) HttpStatusCode.BadRequest);
}
//...
return Ok(myObject);
}
如果您想从控制器中删除此类空值检查,则可以定义自定义属性:
public class CheckModelForNullAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext context)
{
if (context.ActionArguments.Any(k => k.Value == null))
{
context.Result = new BadRequestObjectResult("The model cannot be null");
}
}
}
这样我们就不必为模型在动作中为空而烦恼。
[HttpPost]
[CheckModelForNull]
public async Task<SomeObject> Post([FromBody]InputData inputData)
{
// My attribute protects me from null
// ...
return myObject;
}