public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new HandleErrorAttribute());
filters.Add(new System.Web.Mvc.AuthorizeAttribute());
}

ttribute in the ASP.NET Web API.

Custom Authorize Attribute

in ASP.NET WEB API you can extend "AuthorizeAttribute" to implement custom authorization filter to control the access to the application. I have overridden the "OnAuthorization" method to check custom authorization rules. In this implementation, I am assuming that user will send and receive the data through "HTTP headers".

Following is code example how to implement it.

 Collapse | Copy Code
public class CustomAuthorize : System.Web.Http.AuthorizeAttribute
{
public override void OnAuthorization(
System.Web.Http.Controllers.HttpActionContext actionContext)
{
base.OnAuthorization(actionContext);
if (actionContext.Request.Headers.GetValues("authenticationToken") != null)
{
// get value from header
string authenticationToken = Convert.ToString(
actionContext.Request.Headers.GetValues("authenticationToken").FirstOrDefault());
//authenticationTokenPersistant
// it is saved in some data store
// i will compare the authenticationToken sent by client with
// authenticationToken persist in database against specific user, and act accordingly
if (authenticationTokenPersistant != authenticationToken)
{
HttpContext.Current.Response.AddHeader("authenticationToken", authenticationToken);
HttpContext.Current.Response.AddHeader("AuthenticationStatus", "NotAuthorized");
actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.Forbidden);
return;
} HttpContext.Current.Response.AddHeader("authenticationToken", authenticationToken);
HttpContext.Current.Response.AddHeader("AuthenticationStatus", "Authorized");
return;
}
actionContext.Response =
actionContext.Request.CreateResponse(HttpStatusCode.ExpectationFailed);
actionContext.Response.ReasonPhrase = "Please provide valid inputs";
}
}

Custom Handle Exception attribute:

To implement custom Handle Exception attribute you need to extend "ExceptionFilterAttribute", and override "OnException" method.

You can find the example below:

 Collapse | Copy Code
public class HandleExceptionAttribute : ExceptionFilterAttribute
{
public override void OnException(HttpActionExecutedContext actionExecutedContext)
{
if (actionExecutedContext.Exception != null)
{
var exception = actionExecutedContext.Exception;
var response = new HttpResponseMessage();
response.StatusCode = HttpStatusCode.InternalServerError;
response.ReasonPhrase = exception.Message;
actionExecutedContext.Result = response;
}
}
}
 

This article describes error and exception handling in ASP.NET Web API.

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.

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.

publicProductGetProduct(int id){Product item = repository.Get(id);if(item ==null){thrownewHttpResponseException(HttpStatusCode.NotFound);}return item;}

For more control over the response, you can also construct the entire response message and include it with theHttpResponseException:

publicProductGetProduct(int id){Product item = repository.Get(id);if(item ==null){var resp =newHttpResponseMessage(HttpStatusCode.NotFound){Content=newStringContent(string.Format("No product with ID = {0}", id)),ReasonPhrase="Product ID Not Found"}thrownewHttpResponseException(resp);}return item;}

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. TheHttpResponseException type is a special case, because it is designed specifically for returning an HTTP response.

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 theOnException method.

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, theHandleErrorAttribute class used in MVC does not handle exceptions thrown by Web API controllers.

Here is a filter that converts NotImplementedException exceptions into HTTP status code 501, Not Implemented:

namespaceProductStore.Filters{usingSystem;usingSystem.Net;usingSystem.Net.Http;usingSystem.Web.Http.Filters;publicclassNotImplExceptionFilterAttribute:ExceptionFilterAttribute{publicoverridevoidOnException(HttpActionExecutedContext context){if(context.ExceptionisNotImplementedException){
context.Response=newHttpResponseMessage(HttpStatusCode.NotImplemented);}}}}

The Response property of the HttpActionExecutedContext object contains the HTTP response message that will be sent to the client.

Registering Exception Filters

There are several ways to register a Web API exception filter:

  • By action
  • By controller
  • Globally

To apply the filter to a specific action, add the filter as an attribute to the action:

publicclassProductsController:ApiController{[NotImplExceptionFilter]publicContactGetContact(int id){thrownewNotImplementedException("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]publicclassProductsController:ApiController{// ...}

To apply the filter globally to all Web API controllers, add an instance of the filter to theGlobalConfiguration.Configuration.Filters collection. Exeption filters in this collection apply to any Web API controller action.

GlobalConfiguration.Configuration.Filters.Add(newProductStore.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:

publicstaticclassWebApiConfig{publicstaticvoidRegister(HttpConfiguration config){config.Filters.Add(newProductStore.NotImplExceptionFilterAttribute());// Other configuration code...}}

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:

publicHttpResponseMessageGetProduct(int id){Product item = repository.Get(id);if(item ==null){var message =string.Format("Product with id = {0} not found", id);HttpError err =newHttpError(message);returnRequest.CreateResponse(HttpStatusCode.NotFound, err);}else{returnRequest.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/1.1404NotFoundContent-Type: application/json; charset=utf-8Date:Thu,09Aug201223: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.

Instead of creating the HttpError object directly, you can use the CreateErrorResponse method:

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

CreateErrorResponse is an extension method defined in the System.Net.Http.HttpRequestMessageExtensionsclass. Internally, CreateErrorResponse creates an HttpError instance and then creates an HttpResponseMessagethat contains the HttpError.

HttpError and Model Validation

For model validation, you can pass the model state to CreateErrorResponse, to include the validation errors in the response:

publicHttpResponseMessagePostProduct(Product item){if(!ModelState.IsValid){returnRequest.CreateErrorResponse(HttpStatusCode.BadRequest,ModelState);}// Implementation not shown...}

This example might return the following response:

HTTP/1.1400BadRequestContent-Type: application/json; charset=utf-8Content-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.

Adding Custom Key-Values to 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:

publicHttpResponseMessageGetProduct(int id){Product item = repository.Get(id);if(item ==null){var message =string.Format("Product with id = {0} not found", id);var err =newHttpError(message);err["error_sub_code"]=42;returnRequest.CreateErrorResponse(HttpStatusCode.NotFound, err);}else{returnRequest.CreateResponse(HttpStatusCode.OK, item);}}

Using HttpError with HttpResponseException

The previous examples return an HttpResponseMessage message from the controller action, but you can also useHttpResponseException 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:

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

Exception Handling in ASP.NET Web API的更多相关文章

  1. Exception Handling in ASP.NET Web API webapi异常处理

    原文:http://www.asp.net/web-api/overview/error-handling/exception-handling This article describes erro ...

  2. Global Error Handling in ASP.NET Web API 2(webapi2 中的全局异常处理)

    目前,在Web API中没有简单的方法来记录或处理全局异常(webapi1中).一些未处理的异常可以通过exception filters进行处理,但是有许多情况exception filters无法 ...

  3. ASP.NET Web API之消息[拦截]处理

    标题相当难取,内容也许和您想的不一样,而且网上已经有很多这方面的资料了,我不过是在实践过程中作下记录.废话少说,直接开始. Exception 当服务端抛出未处理异常时,most exceptions ...

  4. ASP.NET Web API系列教程目录

    ASP.NET Web API系列教程目录 Introduction:What's This New Web API?引子:新的Web API是什么? Chapter 1: Getting Start ...

  5. 【ASP.NET Web API教程】4.3 ASP.NET Web API中的异常处理

    原文:[ASP.NET Web API教程]4.3 ASP.NET Web API中的异常处理 注:本文是[ASP.NET Web API系列教程]的一部分,如果您是第一次看本系列教程,请先看前面的内 ...

  6. ASP.NET Web API 2中的错误处理

    前几天在webapi项目中遇到一个问题:Controller构造函数中抛出异常时全局过滤器捕获不到,于是网搜一把写下这篇博客作为总结. HttpResponseException 通常在WebAPI的 ...

  7. ASP.NET Web API系列教程(目录)(转)

    注:微软随ASP.NET MVC 4一起还发布了一个框架,叫做ASP.NET Web API.这是一个用来在.NET平台上建立HTTP服务的Web API框架,是微软的又一项令人振奋的技术.目前,国内 ...

  8. ASP.NET Web API之消息[拦截]处理(转)

    出处:http://www.cnblogs.com/Leo_wl/p/3238719.html 标题相当难取,内容也许和您想的不一样,而且网上已经有很多这方面的资料了,我不过是在实践过程中作下记录.废 ...

  9. [转]ASP.NET Web API系列教程(目录)

    本文转自:http://www.cnblogs.com/r01cn/archive/2012/11/11/2765432.html 注:微软随ASP.NET MVC 4一起还发布了一个框架,叫做ASP ...

随机推荐

  1. 无法关闭的QT程序——思路开阔一下,原来这么简单!

    做一个无法关闭的QT程序(想关闭时要在任务管理器里关闭),看似很难, 其实它并不难,只要让程序在关闭时启动它自身就可以了. 上代码: #include <QtGui> class Temp ...

  2. 【深夜急报,Win10下的Linux子系统之Bash】

    [在Windows下进行的编程人员,你真的需要学习下Linux] 手册:<Linux 命令手册(特洛伊版2.0)> 链接: https://pan.baidu.com/s/1skrVSvV ...

  3. jQuery.each(object, [callback])方法,用于处理json数组

    通用例遍方法,可用于例遍对象和数组. 不同于例遍 jQuery 对象的 $().each() 方法,此方法可用于例遍任何对象.回调函数拥有两个参数:第一个为对象的成员或数组的索引,第二个为对应变量或内 ...

  4. OSCHina技术导向:Java轻量web开发框架——JFinal

    JFinal 是基于 Java 语言的极速 WEB + ORM 框架,其核心设计目标是开发迅速.代码量少.学习简单.功能强大.轻量级.易扩展.Restful.在拥有Java语言所有优势的同时再拥有ru ...

  5. logback.xml配置详解

    先附上本文分析用的例子: <?xml version="1.0" encoding="UTF-8" ?> <configuration> ...

  6. flume【源码分析】分析Flume的启动过程

    h2 { color: #fff; background-color: #7CCD7C; padding: 3px; margin: 10px 0px } h3 { color: #fff; back ...

  7. A Game with Colored Balls

    题目链接 题意: 给一个长度为n的字符串,每次删除字母同样切连续的串,假设有多个,删除最左边的.最长的串.每次删除输出串的字母,每一个字母的下标(1-n) N (1 ≤ N ≤ 106),串仅仅包含r ...

  8. C++ STL源代码学习(map,set内部heap篇)

    stl_heap.h ///STL中使用的是大顶堆 /// Heap-manipulation functions: push_heap, pop_heap, make_heap, sort_heap ...

  9. IOS中的几中观察监听模式

    本文介绍Objective C中实现观察者模式(也被称为广播者/监听者.发布/注册或者通知)的五种方法以及每种方法的价值所在. 该文章将包括: 1 手动广播者和监听者(Broadcaster and ...

  10. 从头开始-06.C语言中预处理指令

    预处理指令 不带参数的宏定义: 格式: #define 宏名 值 作用:提高代码的可读性 在程序编译前把所有出现宏名标示的位置都替换为定义宏的时候,宏名后面的值 带参数的宏定义 格式 #define ...