相关疑难解决方法(0)

在ASP.NET Web API中返回错误的最佳实践

我对我们向客户返回错误的方式感到担忧.

当我们收到错误时,我们通过抛出HttpResponseException立即返回错误:

public void Post(Customer customer)
{
    if (string.IsNullOrEmpty(customer.Name))
    {
        throw new HttpResponseException("Customer Name cannot be empty", HttpStatusCode.BadRequest) 
    }
    if (customer.Accounts.Count == 0)
    {
         throw new HttpResponseException("Customer does not have any account", HttpStatusCode.BadRequest) 
    }
}
Run Code Online (Sandbox Code Playgroud)

或者我们累积所有错误然后发送回客户端:

public void Post(Customer customer)
{
    List<string> errors = new List<string>();
    if (string.IsNullOrEmpty(customer.Name))
    {
        errors.Add("Customer Name cannot be empty"); 
    }
    if (customer.Accounts.Count == 0)
    {
         errors.Add("Customer does not have any account"); 
    }
    var responseMessage = new HttpResponseMessage<List<string>>(errors, HttpStatusCode.BadRequest);
    throw new HttpResponseException(responseMessage);
}
Run Code Online (Sandbox Code Playgroud)

这只是一个示例代码,无论是验证错误还是服务器错误都无关紧要,我只想了解最佳实践,每种方法的优缺点.

c# rest asp.net-web-api

364
推荐指数
8
解决办法
46万
查看次数

标签 统计

asp.net-web-api ×1

c# ×1

rest ×1