澳门太阳娱乐集团官网-太阳集团太阳娱乐登录

【ASP.NET Web API教程】4.3 ASP.NET Web API中的异常处理
分类:脚本专栏

假如在 ASP.NET MVC 应用程序中著录特别新闻,大家只要求在 Global.asax 的 Application_Error 中加多代码就足以了,比方:

注:本文是【ASP.NET Web API体系教程】的一片段,如若你是首先次看本连串教程,请先看眼下的剧情。

【ASP.NET Web API教程】4.3 ASP.NET Web API中的万分管理,api卓殊管理

参照他事他说加以考察页面:

注:本文是【ASP.NET Web API类别教程】的一部分,若是您是首次看本种类教程,请先看日前的内容。

public class MvcApplication : System.Web.HttpApplication{    protected void Application_Error(object sender, EventArgs e)    {        var lastError = Server.GetLastError();        if (lastError != null)        {            Logger.Default.Error("Application_Error", lastError);            Response.StatusCode = 500;            Server.ClearError();        }    }}

Exception Handling in ASP.NET Web API ASP.NET Web API中的极度管理

本文引自:

By Mike Wasson | March 12, 2012
作者:Mike Wasson | 日期:2012-3-12

This article describes error and exception handling in ASP.NET Web API.
本文描述ASP.NET Web API中的错误与那些管理:

  • HttpResponseException
  • Exception Filters
    老大过滤器
  • Registering Exception Filters
    挂号分外过滤器
  • HttpError

Exception Handling in ASP.NET Web API ASP.NET Web API中的极度管理

本文引自:

By Mike Wasson | March 12, 2012
作者:Mike Wasson | 日期:2012-3-12

This article describes error and exception handling in ASP.NET Web API.
正文描述ASP.NET Web API中的错误与特别管理:

  • HttpResponseException
  • Exception Filters
    这个过滤器
  • Registering Exception Filters
    注册格外过滤器
  • HttpError

但这一套在 ASP.NET Web API 中并不适用,其消除办法亦不是很麻烦,大家先创立ExceptionHandlingAttribute(承袭 ExceptionFilterAttribute):

HttpResponseException

What happens if a Web API controller throws an uncaught exception? By default, most exceptions are translated into an HTTP response with status code 500, Internal Server Error.
假诺二个Web API调控器抛出一个未捕捉极度,会时有产生什么样?默许地,大比相当多极其都会被转化成贰个包罗状态码“500 – 内部服务器错误”的HTTP响应。

The HttpResponseException type is a special case. This exception returns any HTTP status code that you specify in the exception constructor. For example, the following method returns 404, Not Found, if the id parameter is not valid.
HttpResponseException(HTTP响应格外)类型是一种独特的情状。这种特别会重临您在十分构造器中内定的别样HTTP状态码。比方,在偏下措施中,如若id参数违法,会回去“404 — 未找到”。

public Product GetProduct(int id) 
{ 
    Product item = repository.Get(id); 
    if (item == null) 
    { 
        throw new HttpResponseException(HttpStatusCode.NotFound); 
    } 
    return item; 
}

For more control over the response, you can also construct the entire response message and include it with the HttpResponseException:
为了对响应举行更多调控,你也能够组织整个响应音讯,并用HttpResponseException来含有它:

public Product GetProduct(int id) 
{ 
    Product item = repository.Get(id); 
    if (item == null) 
    { 
        var resp = new HttpResponseMessage(HttpStatusCode.NotFound) 
        { 
            Content = new StringContent(string.Format("No product with ID = {0}", id)), 
            ReasonPhrase = "Product ID Not Found" 
        } 
        throw new HttpResponseException(resp); 
    } 
    return item; 
}

HttpResponseException

What happens if a Web API controller throws an uncaught exception? By default, most exceptions are translated into an HTTP response with status code 500, Internal Server Error.
一经三个Web API调控器抛出贰个未捕捉至极,会发生什么?暗许地,大好多不胜都会被转化成二个包罗状态码“500 – 内部服务器错误”的HTTP响应。

The HttpResponseException type is a special case. This exception returns any HTTP status code that you specify in the exception constructor. For example, the following method returns 404, Not Found, if the id parameter is not valid.
HttpResponseException(HTTP响应卓殊)类型是一种特别的情状。这种非常会回来您在极度构造器中钦命的其余HTTP状态码。比如,在偏下方式中,假设id参数非法,会重临“404 — 未找到”。

public Product GetProduct(int id) 
{ 
    Product item = repository.Get(id); 
    if (item == null) 
    { 
        throw new HttpResponseException(HttpStatusCode.NotFound); 
    } 
    return item; 
}

For more control over the response, you can also construct the entire response message and include it with the HttpResponseException:
为了对响应进行越多调控,你也得以协会整个响应新闻,并用HttpResponseException来含有它:

public Product GetProduct(int id) 
{ 
    Product item = repository.Get(id); 
    if (item == null) 
    { 
        var resp = new HttpResponseMessage(HttpStatusCode.NotFound) 
        { 
            Content = new StringContent(string.Format("No product with ID = {0}", id)), 
            ReasonPhrase = "Product ID Not Found" 
        } 
        throw new HttpResponseException(resp); 
    } 
    return item; 
}
public class ExceptionHandlingAttribute : ExceptionFilterAttribute{    public override void OnException(HttpActionExecutedContext context)    {        var exception = context.Exception;        if (exception != null)        {            Logger.Default.Error("Application_Error", exception);        }    }}

Exception Filters 万分过滤器

You can customize how Web API handles exceptions by writing an exception filter. An exception filter is executed when a controller method throws any unhandled exception that is not an HttpResponseException exception. The HttpResponseException type is a special case, because it is designed specifically for returning an HTTP response.
通过编写制定叁个可怜过滤器(exception filter),你能够定制Web API怎样管理非常。当一个调节器抛出三个非HttpResponseException分外的未管理非凡时,会实行一个特别过滤器。HttpResponseException类型三个特殊的状态,因为它是专程规划用来回到四个HTTP响应的。

Exception filters implement the System.Web.Http.Filters.IExceptionFilter interface. The simplest way to write an exception filter is to derive from the System.Web.Http.Filters.ExceptionFilterAttribute class and override the OnException method.
十三分过滤器落成System.Web.Http.Filters.IExceptionFilter接口。编写至极过滤器最简便易行的点子是由此System.Web.Http.Filters.ExceptionFilterAttribute类实行派生,同仁一视写其OnException方法。

Exception filters in ASP.NET Web API are similar to those in ASP.NET MVC. However, they are declared in a separate namespace and function separately. In particular, the HandleErrorAttribute class used in MVC does not handle exceptions thrown by Web API controllers.
ASP.NET Web API中的卓殊过滤器要比ASP.NET MVC中的轻巧些。但是,这两侧是在差别的命名空间中扬言的,且是功力独立的。特别是MVC中运用的HandleErrorAttribute类不会处理Web API调节器中抛出的那贰个。

Here is a filter that converts NotImplementedException exceptions into HTTP status code 501, Not Implemented:
以下是将NotImplementedException十分调换来HTTP状态码“501 — 未兑现”的叁个过滤器:

namespace ProductStore.Filters 
{ 
    using System; 
    using System.Net; 
    using System.Net.Http; 
    using System.Web.Http.Filters; 

    public class NotImplExceptionFilterAttribute : ExceptionFilterAttribute  
    { 
        public override void OnException(HttpActionExecutedContext context) 
        { 
            if (context.Exception is NotImplementedException) 
            { 
                context.Response = new HttpResponseMessage(HttpStatusCode.NotImplemented); 
            } 
        } 
    } 
}

The Response property of the HttpActionExecutedContext object contains the HTTP response message that will be sent to the client.
HttpActionExecutedContext对象的Response属性含有将发送给客商端的HTTP响应音信。

Exception Filters 格外过滤器

You can customize how Web API handles exceptions by writing an exception filter. An exception filter is executed when a controller method throws any unhandled exception that is not an HttpResponseException exception. The HttpResponseException type is a special case, because it is designed specifically for returning an HTTP response.
通过编写制定一个非凡过滤器(exception filter),你能够定制Web API怎么着管理特别。当一个调节器抛出多少个非HttpResponseException卓殊的未处理分外时,会举行三个老大过滤器。HttpResponseException类型八个特殊的处境,因为它是非常计划用来回到三个HTTP响应的。

Exception filters implement the System.Web.Http.Filters.IExceptionFilter interface. The simplest way to write an exception filter is to derive from the System.Web.Http.Filters.ExceptionFilterAttribute class and override the OnException method.
特别过滤器达成System.Web.Http.Filters.IExceptionFilter接口。编写分外过滤器最简便的艺术是经过System.Web.Http.Filters.ExceptionFilterAttribute类实行派生,人己一视写其OnException方法。

Exception filters in ASP.NET Web API are similar to those in ASP.NET MVC. However, they are declared in a separate namespace and function separately. In particular, the HandleErrorAttribute class used in MVC does not handle exceptions thrown by Web API controllers.
ASP.NET Web API中的十分过滤器要比ASP.NET MVC中的轻易些。不过,那五头是在差别的命名空间中宣称的,且是效用独立的。非常是MVC中利用的HandleErrorAttribute类不会管理Web API调整器中抛出的不胜。

Here is a filter that converts NotImplementedException exceptions into HTTP status code 501, Not Implemented:
以下是将NotImplementedException分外调换来HTTP状态码“501 — 未完毕”的一个过滤器:

namespace ProductStore.Filters 
{ 
    using System; 
    using System.Net; 
    using System.Net.Http; 
    using System.Web.Http.Filters; 

    public class NotImplExceptionFilterAttribute : ExceptionFilterAttribute  
    { 
        public override void OnException(HttpActionExecutedContext context) 
        { 
            if (context.Exception is NotImplementedException) 
            { 
                context.Response = new HttpResponseMessage(HttpStatusCode.NotImplemented); 
            } 
        } 
    } 
}

The Response property of the HttpActionExecutedContext object contains the HTTP response message that will be sent to the client.
HttpActionExecutedContext对象的Response质量含有将发送给客商端的HTTP响应音信。

然后在 WebApiConfig 中注册下:

Registering Exception Filters 注册非凡过滤器

There are several ways to register a Web API exception filter:
以下是注册Web API非常过滤器的三种方法:

  • By action
    由动作注册
  • By controller
    由控制器注册
  • Globally
    全局注册

To apply the filter to a specific action, add the filter as an attribute to the action:
要把过滤运用于特定的动作,在动作上增加该过滤器的笺注属性:

public class ProductsController : ApiController 
{ 
    [NotImplExceptionFilter]
    public Contact GetContact(int id) 
    { 
        throw new NotImplementedException("This method is not implemented"); 
    } 
}

To apply the filter to all of the actions on a controller, add the filter as an attribute to the controller class:
要把过滤器运用于三个调控器的有着动作,在调整器上加多该过滤器的评释属性:

[NotImplExceptionFilter] 
public class ProductsController : ApiController
{
    // ... 
}

To apply the filter globally to all Web API controllers, add an instance of the filter to the GlobalConfiguration.Configuration.Filters collection. Exeption filters in this collection apply to any Web API controller action.
要全局性地把过滤器运用于全数Web API调整器,将该过滤器的四个实例增多到GlobalConfiguration.Configuration.Filters聚拢。这一个集结中的十分过滤器会使用于其余Web API调节器动作。

GlobalConfiguration.Configuration.Filters.Add(
    new ProductStore.NotImplExceptionFilterAttribute());

If you use the "ASP.NET MVC 4 Web Application" project template to create your project, put your Web API configuration code inside the WebApiConfig class, which is located in the App_Start folder:
假如用的是“ASP.NET MVC 4 Web应用程序”项目模板成立的门类,要把你的Web API配置代码被放在WebApiConfig类中,它位于App_Start文件夹:

public static class WebApiConfig 
{ 
    public static void Register(HttpConfiguration config) 
    { 
        config.Filters.Add(new ProductStore.NotImplExceptionFilterAttribute()); 

        // Other configuration code(其它配置代码)... 
    } 
}

Registering Exception Filters 注册分外过滤器

There are several ways to register a Web API exception filter:
以下是挂号Web API非凡过滤器的三种艺术:

  • By action
    由动作注册
  • By controller
    由调节器注册
  • Globally
    全局注册

To apply the filter to a specific action, add the filter as an attribute to the action:
要把过滤运用于特定的动作,在动作上增添该过滤器的批注属性:

public class ProductsController : ApiController 
{ 
    [NotImplExceptionFilter]
    public Contact GetContact(int id) 
    { 
        throw new NotImplementedException("This method is not implemented"); 
    } 
}

To apply the filter to all of the actions on a controller, add the filter as an attribute to the controller class:
要把过滤器运用于二个调控器的具备动作,在调控器上增加该过滤器的注释属性:

[NotImplExceptionFilter] 
public class ProductsController : ApiController
{
    // ... 
}

To apply the filter globally to all Web API controllers, add an instance of the filter to the GlobalConfiguration.Configuration.Filters collection. Exeption filters in this collection apply to any Web API controller action.
要全局性地把过滤器运用于全数Web API调控器,将该过滤器的叁个实例增添到GlobalConfiguration.Configuration.Filters汇集。这几个集结中的非凡过滤器会选用于任何Web API调整器动作。

GlobalConfiguration.Configuration.Filters.Add(
    new ProductStore.NotImplExceptionFilterAttribute());

If you use the "ASP.NET MVC 4 Web Application" project template to create your project, put your Web API configuration code inside the WebApiConfig class, which is located in the App_Start folder:
即使用的是“ASP.NET MVC 4 Web应用程序”项目模板创立的门类,要把您的Web API配置代码被放在WebApiConfig类中,它位于App_Start文件夹:

public static class WebApiConfig 
{ 
    public static void Register(HttpConfiguration config) 
    { 
        config.Filters.Add(new ProductStore.NotImplExceptionFilterAttribute()); 

        // Other configuration code(其它配置代码)... 
    } 
}
public static class WebApiConfig{    public static void Register(HttpConfiguration config)    {        // Web API configuration and services        config.Filters.Add(new ExceptionHandlingAttribute;        // Web API routes        config.MapHttpAttributeRoutes();        config.Routes.MapHttpRoute(            name: "DefaultApi",            routeTemplate: "api/{controller}/{id}",            defaults: new { id = RouteParameter.Optional }        );    }}

HttpError

The HttpError object provides a consistent way to return error information in the response body. The following example shows how to return HTTP status code 404 (Not Found) with an HttpError in the response body:
HttpError目的为在响应体中回到错误消息提供了对应的艺术。以下示例演示了何等用HttpError在响应体中回到HTTP状态码“404 — 未找到”:

public HttpResponseMessage GetProduct(int id) 
{ 
    Product item = repository.Get(id); 
    if (item == null) 
    {
        var message = string.Format("Product with id = {0} not found", id); 
        HttpError err = new HttpError(message); 
        return Request.CreateResponse(HttpStatusCode.NotFound, err); 
    } 
    else 
    { 
        return Request.CreateResponse(HttpStatusCode.OK, item); 
    } 
}

In this example, if the method is successful, it returns the product in the HTTP response. But if the requested product is not found, the HTTP response contains an HttpError in the request body. The response might look like the following:
在这几个例子中,若是该措施成功,它会在HTTP响应中回到产品。但假设所须求的出品未找到,则HTTP响应会在乞请体中包涵三个HttpError。该响应看上去大约像这样:

HTTP/1.1 404 Not Found 
Content-Type: application/json; charset=utf-8 
Date: Thu, 09 Aug 2012 23:27:18 GMT 
Content-Length: 51 

{ 
  "Message": "Product with id = 12 not found" 
}

Notice that the HttpError was serialized to JSON in this example. One advantage of using HttpError is that it goes through the same content-negotiation and serialization process as any other strongly-typed model.
只顾,在那么些事例中,HttpError会被体系化成JSON。使用HttpError的三个好处是,与别的强类型模型同样,会开展一样的“内容协商”(本类别化教程的第6.2小节 — 译者注)和系列化进度。

Instead of creating the HttpError object directly, you can use the CreateErrorResponse method:
代表直接成立HttpError目的的一种艺术是,你能够采取CreateErrorResponse方法:

public HttpResponseMessage GetProduct(int id) 
{ 
    Product item = repository.Get(id); 
    if (item == null) 
    { 
        var message = string.Format("Product with id = {0} not found", id); 
        return Request.CreateErrorResponse(HttpStatusCode.NotFound, message); 
    } 
    else 
    { 
        return Request.CreateResponse(HttpStatusCode.OK, item); 
    } 
}

CreateErrorResponse is an extension method defined in the System.Net.Http.HttpRequestMessageExtensions class. Internally, CreateErrorResponse creates an HttpError instance and then creates an HttpResponseMessage that contains the HttpError.
CreateErrorResponse是在System.Net.Http.HttpRequestMessageExtensions类中定义的多个恢宏方法。本质上,CreateErrorResponse会创制多少个HttpError实例,然后创立三个含有该HttpErrorHttpResponseMessage

HttpError

The HttpError object provides a consistent way to return error information in the response body. The following example shows how to return HTTP status code 404 (Not Found) with an HttpError in the response body:
HttpError目的为在响应体中回到错误新闻提供了对应的格局。以下示例演示了怎么着用HttpError在响应体中回到HTTP状态码“404 — 未找到”:

public HttpResponseMessage GetProduct(int id) 
{ 
    Product item = repository.Get(id); 
    if (item == null) 
    {
        var message = string.Format("Product with id = {0} not found", id); 
        HttpError err = new HttpError(message); 
        return Request.CreateResponse(HttpStatusCode.NotFound, err); 
    } 
    else 
    { 
        return Request.CreateResponse(HttpStatusCode.OK, item); 
    } 
}

In this example, if the method is successful, it returns the product in the HTTP response. But if the requested product is not found, the HTTP response contains an HttpError in the request body. The response might look like the following:
在那一个事例中,若是该格局成功,它会在HTTP响应中回到产品。但假使所乞请的成品未找到,则HTTP响应会在乞请体中富含二个HttpError。该响应看上去大约像这么:

HTTP/1.1 404 Not Found 
Content-Type: application/json; charset=utf-8 
Date: Thu, 09 Aug 2012 23:27:18 GMT 
Content-Length: 51 

{ 
  "Message": "Product with id = 12 not found" 
}

Notice that the HttpError was serialized to JSON in this example. One advantage of using HttpError is that it goes through the same content-negotiation and serialization process as any other strongly-typed model.
注意,在这些例子中,HttpError会被类别化成JSON。使用HttpError的叁个功利是,与任何强类型模型一样,会议及展览开一样的“内容协商”(本种类化教程的第6.2小节 — 译者注)和种类化进度。

Instead of creating the HttpError object directly, you can use the CreateErrorResponse method:
取代直接开立HttpError对象的一种情势是,你能够使用CreateErrorResponse方法:

public HttpResponseMessage GetProduct(int id) 
{ 
    Product item = repository.Get(id); 
    if (item == null) 
    { 
        var message = string.Format("Product with id = {0} not found", id); 
        return Request.CreateErrorResponse(HttpStatusCode.NotFound, message); 
    } 
    else 
    { 
        return Request.CreateResponse(HttpStatusCode.OK, item); 
    } 
}

CreateErrorResponse is an extension method defined in the System.Net.Http.HttpRequestMessageExtensions class. Internally, CreateErrorResponse creates an HttpError instance and then creates an HttpResponseMessage that contains the HttpError.
CreateErrorResponse是在System.Net.Http.HttpRequestMessageExtensions类中定义的二个增加方法。本质上,CreateErrorResponse会创造四个HttpError实例,然后创制三个蕴涵该HttpErrorHttpResponseMessage

或然大家在 Action 上边加多 ExceptionHandlingAttribute 属性:

HttpError and Model Validation HttpError与模型验证

For model validation, you can pass the model state to CreateErrorResponse, to include the validation errors in the response:
对于模型验证,你能够把模型状态传递给CreateErrorResponse,以便在响应中包括验证错误:

public HttpResponseMessage PostProduct(Product item) 
{ 
    if (!ModelState.IsValid) 
    { 
        return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState); 
    } 

    // Implementation not shown(未列出实现代码)... 
}

This example might return the following response:
此例也许会回去以下响应:

HTTP/1.1 400 Bad Request 
Content-Type: application/json; charset=utf-8 
Content-Length: 320 

{ 
  "Message": "The request is invalid.", 
  "ModelState": { 
    "item": [ 
      "Required property 'Name' not found in JSON. Path '', line 1, position 14." 
    ], 
    "item.Name": [ 
      "The Name field is required." 
    ], 
    "item.Price": [ 
      "The field Price must be between 0 and 999." 
    ] 
  } 
}

For more information about model validation, see Model Validation in ASP.NET Web API.
关于模型验证的越多消息,参阅“ASP.NET Web API中的模型验证”(本连串教程的第6.4小节 — 译者注)。

HttpError and Model Validation HttpError与模型验证

For model validation, you can pass the model state to CreateErrorResponse, to include the validation errors in the response:
对此模型验证,你能够把模型状态传递给CreateErrorResponse,以便在响应中饱含验证错误:

public HttpResponseMessage PostProduct(Product item) 
{ 
    if (!ModelState.IsValid) 
    { 
        return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState); 
    } 

    // Implementation not shown(未列出实现代码)... 
}

This example might return the following response:
此例恐怕会回到以下响应:

HTTP/1.1 400 Bad Request 
Content-Type: application/json; charset=utf-8 
Content-Length: 320 

{ 
  "Message": "The request is invalid.", 
  "ModelState": { 
    "item": [ 
      "Required property 'Name' not found in JSON. Path '', line 1, position 14." 
    ], 
    "item.Name": [ 
      "The Name field is required." 
    ], 
    "item.Price": [ 
      "The field Price must be between 0 and 999." 
    ] 
  } 
}

For more information about model validation, see Model Validation in ASP.NET Web API.
至于模型验证的更加的多消息,参阅“ASP.NET Web API中的模型验证”(本类别教程的第6.4小节 — 译者注)。

public class ValuesController : ApiController{    [ExceptionHandlingAttribute]    public IEnumerable<string> Get()    {        return new string[] { "value1", "value2" };    }}

Adding Custom Key-Values to HttpError 将自定义“键-值”增加到HttpError

The HttpError class is actually a key-value collection (it derives from Dictionary<string, object>), so you can add your own key-value pairs:
HttpError类实际上是二个“键-值”集结(它派生于Dictionary<string, object>),由此你能够加上本人的“键-值”对:

public HttpResponseMessage GetProduct(int id) 
{ 
    Product item = repository.Get(id); 

    if (item == null) 
    { 
        var message = string.Format("Product with id = {0} not found", id); 
        var err = new HttpError(message); 
        err["error_sub_code"] = 42; 
        return Request.CreateErrorResponse(HttpStatusCode.NotFound, err); 
    } 
    else 
    { 
        return Request.CreateResponse(HttpStatusCode.OK, item); 
    } 
}

Adding Custom Key-Values to HttpError 将自定义“键-值”增多到HttpError

The HttpError class is actually a key-value collection (it derives from Dictionary<string, object>), so you can add your own key-value pairs:
HttpError类实际上是一个“键-值”集结(它派生于Dictionary<string, object>),由此你能够加上本身的“键-值”对:

public HttpResponseMessage GetProduct(int id) 
{ 
    Product item = repository.Get(id); 

    if (item == null) 
    { 
        var message = string.Format("Product with id = {0} not found", id); 
        var err = new HttpError(message); 
        err["error_sub_code"] = 42; 
        return Request.CreateErrorResponse(HttpStatusCode.NotFound, err); 
    } 
    else 
    { 
        return Request.CreateResponse(HttpStatusCode.OK, item); 
    } 
}

假设日志未有记录以来,须要在 Global.asax.cs 中的 Application_Start 增多如下代码:

Using HttpError with HttpResponseException 以HttpResponseException来使用HttpError

The previous examples return an HttpResponseMessage message from the controller action, but you can also use HttpResponseException to return an HttpError. This lets you return a strongly-typed model in the normal success case, while still returning HttpError if there is an error:
近期的事例是从调节器动作再次回到多少个HttpResponseMessage新闻,但您也能够行使HttpResponseException来回到四个HttpError。那让您可见在健康成功景色下重回强类型模型,而在有错误时,仍重回HttpError

public Product GetProduct(int id) 
{ 
    Product item = repository.Get(id); 
    if (item == null) 
    { 
        var message = string.Format("Product with id = {0} not found", id); 
        throw new HttpResponseException( 
            Request.CreateErrorResponse(HttpStatusCode.NotFound, message)); 
    } 
    else 
    { 
        return item; 
    } 
}

 

看完此文若是以为全体收获,请给个推荐;)

 

Using HttpError with HttpResponseException 以HttpResponseException来使用HttpError

The previous examples return an HttpResponseMessage message from the controller action, but you can also use HttpResponseException to return an HttpError. This lets you return a strongly-typed model in the normal success case, while still returning HttpError if there is an error:
前面包车型客车事例是从调控器动作重返贰个HttpResponseMessage音讯,但您也足以运用HttpResponseException来回到贰个HttpError。那让你可以在符合规律成功景观下回到强类型模型,而在有荒唐时,仍重临HttpError

public Product GetProduct(int id) 
{ 
    Product item = repository.Get(id); 
    if (item == null) 
    { 
        var message = string.Format("Product with id = {0} not found", id); 
        throw new HttpResponseException( 
            Request.CreateErrorResponse(HttpStatusCode.NotFound, message)); 
    } 
    else 
    { 
        return item; 
    } 
}

 

看完此文如果以为全部收获,请给个推荐

 

Web API教程】4.3 ASP.NET Web API中的非常管理,api格外管理 仿照效法页面: ...

public class MvcApplication : System.Web.HttpApplication{    protected void Application_Start()    {        GlobalConfiguration.Configuration.IncludeErrorDetailPolicy = IncludeErrorDetailPolicy.Always;        ....    }}

参照他事他说加以考察资料:

  • How do I log ALL exceptions globally for a C# MVC4 WebAPI app?
  • Global Error Handling in ASP.NET Web API 2

本文由澳门太阳娱乐集团官网发布于脚本专栏,转载请注明出处:【ASP.NET Web API教程】4.3 ASP.NET Web API中的异常处理

上一篇:太阳集团太阳娱乐登录LOJ#6283. 数列分块入门 7 下一篇:【太阳集团太阳娱乐登录】php将数组输出为.csv文
猜你喜欢
热门排行
精彩图文