在日常进行web开发中难免会遇到一些情况需要返回非200的异常响应,在代码中应当如何实现呢?
HttpResponseException
使用HttpResponseException可以在其构造函数中声明所有Http状态码对应的异常。例如:
throw new HttpResponseException(HttpStatusCode.BadRequest); //400
throw new HttpResponseException(HttpStatusCode.Unauthorized); //401
throw new HttpResponseException(HttpStatusCode.Forbidden); //403
throw new HttpResponseException(HttpStatusCode.NotFound); //404
通过创建一个HttpResponseException实例,并声明具体的Http状态码,就可以抛出指定的webapi异常。
有时我们想在抛出的异常中添加对异常的一些描述,则可以通过创建 HttpResponse Message来实现。
throw new HttpResponseException(new HttpResponseMessage(HttpStatueCode.BadRequest){Content = new StringContent("自定义描述")});
WebApi2
在WebApi2中,可以用更简单的方法来实现:
return Ok();//200
return Ok(new {message = "自定义描述"});//200
return NotFound();//404
更多内容慢慢更…