日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > asp.net >内容正文

asp.net

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

發布時間:2023/12/13 asp.net 24 豆豆
生活随笔 收集整理的這篇文章主要介紹了 ASP.NET Web API之消息[拦截]处理(转) 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

出處:http://www.cnblogs.com/Leo_wl/p/3238719.html

標題相當難取,內容也許和您想的不一樣,而且網上已經有很多這方面的資料了,我不過是在實踐過程中作下記錄。廢話少說,直接開始。

Exception


當服務端拋出未處理異常時,most exceptions are translated into an HTTP response with status code 500, Internal Server Error.當然我們也可以拋出一個特殊的異常HttpResponseException,它將被直接寫入響應流,而不會被轉成500。

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

有時要對服務端異常做一封裝,以便對客戶端隱藏具體細節,或者統一格式,那么可創建一繼承自System.Web.Http.Filters.ExceptionFilterAttribute的特性,如下:

public class APIExceptionFilterAttribute : ExceptionFilterAttribute {public override void OnException(HttpActionExecutedContext context){//業務異常if (context.Exception is BusinessException){context.Response = new HttpResponseMessage { StatusCode = System.Net.HttpStatusCode.ExpectationFailed };BusinessException exception = (BusinessException)context.Exception;context.Response.Headers.Add("BusinessExceptionCode", exception.Code);context.Response.Headers.Add("BusinessExceptionMessage", exception.Message);}//其它異常else{context.Response = new HttpResponseMessage { StatusCode = System.Net.HttpStatusCode.InternalServerError };}} }

然后將該Attribute應用到action或controller,或者GlobalConfiguration.Configuration.Filters.Add(new?APIExceptionFilterAttribute());使之應用于所有action(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:config.Filters.Add(newProductStore.NotImplExceptionFilterAttribute());)。當然,在上述代碼中,我們也可以在OnException方法中直接拋出HttpResponseException,效果是一樣的。

Note: Something to have in mind is that the ExceptionFilterAttribute will be ignored if the ApiController action method throws a HttpResponseException;If something goes wrong in the ExceptionFilterAttribute and an exception is thrown that is not of type HttpResponseException, a formatted exception will be thrown with stack trace etc to the client.

如果要返回給客戶端的不僅僅是一串字符串,比如是json對象,那么可以使用HttpError這個類。

以上知識主要來自Exception Handling in ASP.NET Web API。

ActionFilterAttribute、ApiControllerActionInvoker?


有時要在action執行前后做額外處理,那么ActionFilterAttribute和ApiControllerActionInvoker就派上用場了。比如客戶端請求發過來的參數為用戶令牌字符串token,我們要在action執行之前先將其轉為action參數列表中對應的用戶編號ID,如下:?

public class TokenProjectorAttribute : ActionFilterAttribute {private string _userid = "userid";public string UserID{get { return _userid; }set { _userid = value; }}public override void OnActionExecuting(HttpActionContext actionContext){if (!actionContext.ActionArguments.ContainsKey(UserID)){//參數列表中不存在userid,寫入日志//……var response = new HttpResponseMessage();response.Content = new StringContent("用戶信息轉換異常.");response.StatusCode = HttpStatusCode.Conflict;//在這里為了不繼續走流程,要throw出來,才會立馬返回到客戶端throw new HttpResponseException(response);}//userid系統賦值actionContext.ActionArguments[UserID] = actionContext.Request.Properties["shumi_userid"];base.OnActionExecuting(actionContext);}public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext){base.OnActionExecuted(actionExecutedContext);} }

ActionFilterAttribute如何應用到action,和前面的ExceptionFilterAttribute類似。

ApiControllerActionInvoker以上述Exception為例:

public class ServerAPIControllerActionInvoker : ApiControllerActionInvoker {public override Task<HttpResponseMessage> InvokeActionAsync(HttpActionContext actionContext, CancellationToken cancellationToken){//對actionContext做一些預處理//……var result = base.InvokeActionAsync(actionContext, cancellationToken);if (result.Exception != null && result.Exception.GetBaseException() != null){var baseException = result.Exception.GetBaseException();if (baseException is BusinessException){return Task.Run<HttpResponseMessage>(() =>{var response = new HttpResponseMessage(HttpStatusCode.ExpectationFailed);BusinessException exception = (BusinessException)baseException;response.Headers.Add("BusinessExceptionCode", exception.Code);response.Headers.Add("BusinessExceptionMessage", exception.Message);return response;});}else{return Task.Run<HttpResponseMessage>(() => new HttpResponseMessage(HttpStatusCode.InternalServerError));}}return result;} }

然后注冊至GlobalConfiguration.Configuration.Services中。由于ApiControllerActionInvoker乃是影響全局的,所以若要對部分action進行包裝處理,應該優先選擇ActionFilterAttribute。?

DelegatingHandler


前面的攔截都發生在請求已被路由至對應的action后發生,有一些情況需要在路由之前就做預先處理,或是在響應流返回過程中做后續處理,這時我們就要用到DelegatingHandler。比如對請求方的身份驗證,當驗證未通過時直接返回錯誤信息,否則進行后續調用。

public class AuthorizeHandler : DelegatingHandler {private static IAuthorizer _authorizer = null;static AuthorizeHandler(){ }protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken){if (request.Method == HttpMethod.Post){var querystring = HttpUtility.ParseQueryString(request.RequestUri.Query);var formdata = request.Content.ReadAsFormDataAsync().Result;if (querystring.AllKeys.Intersect(formdata.AllKeys).Count() > 0){return SendError("請求參數有重復.", HttpStatusCode.BadRequest);}}//請求方身份驗證AuthResult result = _authorizer.AuthRequest(request);if (!result.Flag){return SendError(result.Message, HttpStatusCode.Unauthorized);}request.Properties.Add("shumi_userid", result.UserID);return base.SendAsync(request, cancellationToken);}private Task<HttpResponseMessage> SendError(string error, HttpStatusCode code){var response = new HttpResponseMessage();response.Content = new StringContent(error);response.StatusCode = code;return Task<HttpResponseMessage>.Factory.StartNew(() => response);} }

?參考資料:

  • ASP.NET Web API Exception Handling
  • Implementing message handlers to track your ASP.NET Web API usage
  • MVC4 WebAPI(二)——Web API工作方式
  • Asp.Net MVC及Web API框架配置會碰到的幾個問題及解決方案

轉載請注明原文出處:http://www.cnblogs.com/newton/p/3238082.html

轉載于:https://www.cnblogs.com/smileberry/p/7093326.html

總結

以上是生活随笔為你收集整理的ASP.NET Web API之消息[拦截]处理(转)的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。

主站蜘蛛池模板: 欧美成人国产精品一区二区 | 久久久精品小视频 | 欧美天天色 | 亚洲激情欧美色图 | 国产视频久久久久久久 | 农民工hdxxxx性中国 | 69国产在线 | 日日舔夜夜操 | 国产精品88久久久久久妇女 | 美国式禁忌1980 | 亚洲成人自拍网 | 国产精品久久久一区二区 | 国产丝袜视频在线 | 中文字幕免费播放 | 国产男女猛烈无遮挡免费视频 | 国产又猛又粗 | 日韩精品无码一区二区 | 天天射夜夜爽 | 亚洲国产精品无码久久久久高潮 | 丝袜美腿av在线 | 少妇一级淫片免费观看 | 国产av无码专区亚洲av毛片搜 | 免费成人国产 | 欧美日韩国内 | 国产一区二区视频在线免费观看 | 小优视频污 | 色月婷婷 | 免费一级欧美片在线播放 | 爱插网 | 日本成人精品视频 | 中文字幕日韩精品一区 | 欧洲自拍一区 | 亚洲AV无码精品国产 | 丝袜人妻一区二区 | 性高潮久久久久久久久久 | 五月天精品在线 | 日韩三级黄色 | 欧美日本一道 | 日本一道本在线 | 日本不卡一区二区 | 久草国产在线观看 | 国产精品视频999 | 手机在线看片福利 | 韩国视频一区二区 | 天天干干 | 国产wwww| 中文字幕人成人乱码亚洲电影 | 久久久久久久影视 | 欧美日韩观看 | 欧美资源在线观看 | 国产精品国产精品国产专区不卡 | 国产毛片毛片毛片毛片毛片毛片 | 午夜国产一级 | 欧美 变态 另类 人妖 | 国产黄色在线免费观看 | 国产成人无码久久久精品天美传媒 | 麻豆婷婷 | 国产老熟女一区二区三区 | 国产三级漂亮女教师 | 亚洲狠狠婷婷综合久久久久图片 | 亲子乱aⅴ一区二区三区 | 91看片淫黄大片91桃色 | 日韩精品在线一区 | 中文字幕第15页 | 久久久久麻豆v国产精华液好用吗 | 国产淫片av片久久久久久 | 大桥未久视频在线观看 | 国产a级网站 | aaaaaaa毛片| 蜜桃成人免费视频 | 狠狠操伊人 | 贝利弗山的秘密1985版免费观看 | 婷婷射丁香 | 波多野结衣高清视频 | 免费观看成年人网站 | 国产做爰xxxⅹ性视频国 | 欧美综合亚洲图片综合区 | 深爱五月网| 在线免费看污片 | 日韩一二三四区 | 中国女人做爰视频 | 成人h动漫精品一区二区无码 | 亚洲乱亚洲乱 | 琪琪午夜伦理 | 免费看女生裸体视频 | 久久精品黄 | wwwxxx国产| 911av| 91成人入口| 国产精品18久久久久久久久 | aa视频在线观看 | 麻豆传媒在线观看 | 中文一区二区在线 | 五月婷婷婷婷 | 中文字幕精品久久久久人妻红杏ⅰ | 嫩草视频在线观看免费 | 亚洲AV无码精品一区二区三区 | 精品自拍视频在线观看 | 色综合天天操 |