相关疑难解决方法(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万
查看次数

如何将状态401从WebAPI返回到AngularJS并包含自定义消息?

在我的WebAPI类中,ApiController我打了一个调用,例如:

string myCustomMessage = .....;

throw new HttpResponseException(
    new HttpResponseMessage(HttpStatusCode.Unauthorized)
        { ReasonPhrase = myCustomMessage });
Run Code Online (Sandbox Code Playgroud)

当我使用AngularJS $resource服务调用时,我会在状态字段中获得响应的401,在promise的catch块中.401比赛HttpStatusCode.Unauthorized,所以一切都很好.

但问题是响应的数据字段为空(null).我没有得到myCustomMessage返回.

现在,如果不是抛出HttpResponseException异常,我只是抛出一条Exception带有消息的常规消息,该消息确实使它回转到Angular.

我需要能够做到这两点:从服务器返回自定义消息,以及返回的状态代码是我想要的,在本例中为401.

谁知道如何做到这一点?

[编辑] 解决方案:

 throw new HttpResponseException(
     Request.CreateErrorResponse(HttpStatusCode.Unauthorized, myCustomMessage));
Run Code Online (Sandbox Code Playgroud)

javascript asp.net-web-api angularjs

11
推荐指数
1
解决办法
1万
查看次数

标签 统计

asp.net-web-api ×2

angularjs ×1

c# ×1

javascript ×1

rest ×1