SelfHosting ApiController,如何返回错误

时间:2018-01-09 10:02:00

标签: c# asp.net-web-api http-status-code-404 owin self-hosting

我已使用unicode创建自托管API控制器。它可以HttpGetCustomer Customer对象。

通过Id获取[RoutePrefix("test")] public class MyTestController : ApiController { [Route("getcustomer")] [HttpGet] public Customer GetCustomer(int customerId) { // as a test: react as if this customer exists: return new Customer() { Id = customerId, Name = "John Doe", }; } ... } 的(简化)函数是:

HttpResponseMessage

这很好用。在我的客户端,我可以通过Id向该测试服务器询问客户,并获得具有预期数据的客户。

显然,调用函数知道如何将我返回的Customer包装到一个可以传输给我的客户端的对象([Route("getcustomer")] [HttpGet] public Customer GetCustomer(int customerId) { // as a test: only customer 1 exists if (customerId == 1) { return new Customer() { Id = customerId, Name = "John Doe", }; } else { // TODO: make sure 404 Err not found returned. } } ?)中。

下一步:如果找不到客户,则返回错误404.

2:56:41 PM  [mysql]     Error: MySQL shutdown unexpectedly.<br>
2:56:41 PM  [mysql]     This may be due to a blocked port, missing dependencies, <br>
2:56:41 PM  [mysql]     improper privileges, a crash, or a shutdown by another method.<br>
2:56:41 PM  [mysql]     Press the Logs button to view error logs and check<br>
2:56:41 PM  [mysql]     the Windows Event Viewer for more clues<br>
2:56:41 PM  [mysql]     If you need more help, copy and post this<br>
2:56:41 PM  [mysql]     entire log window on the forums<br>

怎么做?抛出异常?调用其中一个WebApi函数来通知应该返回错误404而不是我返回的客户?

2 个答案:

答案 0 :(得分:8)

返回IHttpActionResult代替:

[Route("getcustomer")]
[HttpGet]
public IHttpActionResult GetCustomer(int customerId)
{    // as a test: only customer 1 exists
    if (customerId == 1)
    {
        return Ok(new Customer()
        {
            Id = customerId,
            Name = "John Doe",
        });
    }

    // TODO: make sure 404 Err not found returned.
    return NotFound();
}

答案 1 :(得分:0)

您可以将返回值更改为IHttpActionResult并返回System.Web.Http.Results.OkResultSystem.Web.Http.Results.NotFoundResult

然而,一个类似于您通常所做的更简单的解决方案是抛出System.Web.Http.HttpResponseException.

构造函数采用System.Net.HttpStatusCode。调用者会捕获异常并将其转换为相应的响应。

[Route("getcustomer")]
[HttpGet]
public Customer GetCustomer(int customerId)
{    // as a test: only customer 1 exists
    if (customerId == 1)
    {

    };   
    else
    {
       throw new HttpResponseException(System.Net.HttpStatusCode.NotFound);
    }
}