這篇文章將為大家詳細(xì)講解有關(guān).Net WebApi消息攔截器MessageHandler,文章內(nèi)容質(zhì)量較高,因此小編分享給大家做個參考,希望大家閱讀完這篇文章后對相關(guān)知識有一定的了解。
為北海街道等地區(qū)用戶提供了全套網(wǎng)頁設(shè)計制作服務(wù),及北海街道網(wǎng)站建設(shè)行業(yè)解決方案。主營業(yè)務(wù)為成都做網(wǎng)站、成都網(wǎng)站設(shè)計、北海街道網(wǎng)站設(shè)計,以傳統(tǒng)方式定制建設(shè)網(wǎng)站,并提供域名空間備案等一條龍服務(wù),秉承以專業(yè)、用心的態(tài)度為用戶提供真誠的服務(wù)。我們深信只要達(dá)到每一位用戶的要求,就會得到認(rèn)可,從而選擇與我們長期合作。這樣,我們也可以走得更遠(yuǎn)!消息攔截器是一個類,接收 HTTP request并返回 HTTP response,Message handler 繼承自抽象類 HttpMessageHandler
可以自定義 MessageHandler,消息攔截器的作用如:
讀取或更改請求頭 request headers
添加 response headers
在到達(dá) controller 之前,進(jìn)行參數(shù)驗證
自定義 Message Handlers
自定義 MessageHandler
需要繼承 System.Net.Http.DelegatingHander
并且重載SendAsync方法
Task<HttpResponseMessage> SendAsync( HttpRequestMessage request, CancellationToken cancellationToken);
這個方法的一般的處理流程是
處理請求信息
調(diào)用base.SendAsync
方法,吧請求發(fā)送給內(nèi)部處理
內(nèi)部處理完成之后,返回 response message
(這個過程是異步的)
處理response
之后,返回給調(diào)用者
public class MessageHandler1 : DelegatingHandler { protected async override Task<HttpResponseMessage> SendAsync( HttpRequestMessage request, CancellationToken cancellationToken) { Debug.WriteLine("Process request"); // Call the inner handler. var response = await base.SendAsync(request, cancellationToken); Debug.WriteLine("Process response"); return response; } }
消息攔截器生效
在WebApiConfig
中注冊相關(guān)
public static class WebApiConfig { public static void Register(HttpConfiguration config) { config.MessageHandlers.Add(new MessageHandler1()); config.MessageHandlers.Add(new MessageHandler2()); // Other code not shown... } }
https 請求攔截器
要求所有的請求都必須是https的請求,可以自定義一個https的攔截器,如果是https請求,就繼續(xù)處理,否則就返回相關(guān)的提示信息
public class RequireHttpsHandler : DelegatingHandler { public RequireHttpsHandler(int httpsPort) { _httpsPort = httpsPort; } public RequireHttpsHandler() : this(443) { } protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) { //判斷是否是 https 請求 if (request.RequestUri.Scheme == Uri.UriSchemeHttps) return base.SendAsync(request, cancellationToken); var response = CreateResponse(request); var tcs = new TaskCompletionSource<HttpResponseMessage>(); tcs.SetResult(response); return tcs.Task; } private HttpResponseMessage CreateResponse(HttpRequestMessage request) { HttpResponseMessage response; var uri = new UriBuilder(request.RequestUri); uri.Scheme = Uri.UriSchemeHttps; uri.Port = _httpsPort; var body = string.Format("HTTPS is required<br/>The resource can be found at <a href=\"{0}\">{0}</a>.", uri.Uri.AbsoluteUri); if (request.Method.Equals(HttpMethod.Get) || request.Method.Equals(HttpMethod.Head)) { response = request.CreateResponse(HttpStatusCode.Found); response.Headers.Location = uri.Uri; if (request.Method.Equals(HttpMethod.Get)) response.Content = new StringContent(body, Encoding.UTF8, "text/html"); } else { response = request.CreateResponse(HttpStatusCode.NotFound); response.Content = new StringContent(body, Encoding.UTF8, "text/html"); } return response; } }
Enable CORS 攔截器
public class SimpleCorsHandler : DelegatingHandler { private const string origin = "Origin"; private const string accessControlRequestMethod = "Access-Control-Request-Method"; private const string accessControlRequestHeaders = "Access-Control-Request-Headers"; private const string accessControlAllowOrigin = "Access-Control-Allow-Origin"; private const string accessControlAllowMethods = "Access-Control-Allow-Methods"; private const string accessControlAllowHeaders = "Access-Control-Allow-Headers"; protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) { var isCorsRequest = request.Headers.Contains(origin); var isPreflightRequest = request.Method == HttpMethod.Options; if (isCorsRequest) { if (isPreflightRequest) { return Task.Factory.StartNew(() => { var response = new HttpResponseMessage(HttpStatusCode.OK); response.Headers.Add(accessControlAllowOrigin, request.Headers.GetValues(origin).First()); var currentAccessControlRequestMethod = request.Headers.GetValues(accessControlRequestMethod). FirstOrDefault(); if (currentAccessControlRequestMethod != null) { response.Headers.Add(accessControlAllowMethods, currentAccessControlRequestMethod); } var requestedHeaders = string.Join(", ", request.Headers.GetValues(accessControlRequestHeaders)); if (!string.IsNullOrEmpty(requestedHeaders)) { response.Headers.Add(accessControlAllowHeaders, requestedHeaders); } return response; }, cancellationToken); } else { return base.SendAsync(request, cancellationToken).ContinueWith(t => { var resp = t.Result; resp.Headers.Add( accessControlAllowOrigin, request.Headers.GetValues(origin).First()); return resp; }); } } else { return base.SendAsync(request, cancellationToken); } } }
關(guān)于.Net WebApi消息攔截器MessageHandler就分享到這里了,希望以上內(nèi)容可以對大家有一定的幫助,可以學(xué)到更多知識。如果覺得文章不錯,可以把它分享出去讓更多的人看到。
本文名稱:.NetWebApi消息攔截器MessageHandler-創(chuàng)新互聯(lián)
本文路徑:http://muchs.cn/article8/pggip.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供網(wǎng)站排名、網(wǎng)站營銷、ChatGPT、外貿(mào)建站、Google、做網(wǎng)站
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時需注明來源: 創(chuàng)新互聯(lián)