[筆記][WebAPI][MessageHandler]在MessageHandler中讀取(get)寫入(set) Cookie

  • 519
  • 0

[筆記][WebAPI][MessageHandler]在MessageHandler中讀取(get)寫入(set) Cookie

緣起:

小喵想研究 WebAPI 中,怎麼樣去處理CSRF的防護,在ASP.NET WebForm中,會自動產生「確認碼」放在HiddenFileld,並且每次接受Request的時候會自動檢查。那麼在WebAPI中,應該用什麼樣的方式來處理呢?小喵想到,或許可以用 MessageHandler 搭配 Cookie來處理。這一篇就來記錄怎麼在 Message Handler 中,存取Cookie

MessageHandler檔案

首先,先新增 MessageHandler 檔案。在 Models 中,新增一個類別,內容如下:

Imports System.Net.Http
Imports System.Net.Http.Headers

Public Class TestMessageHandler
    Inherits DelegatingHandler

    Protected Overrides Async Function SendAsync(request As HttpRequestMessage, cancellationToken As Threading.CancellationToken) As Threading.Tasks.Task(Of HttpResponseMessage)

        '處理Request
        Dim TestID As String = getCookie(request, "TestID")


        '透過非同步方式運作,這裡來承接回傳時的response內容
        Dim response = Await MyBase.SendAsync(request, cancellationToken)

        TestID = Format(Now, "yyyyMMddHHmmss") & Guid.NewGuid().ToString.ToUpper

        Dim tCookie As New CookieHeaderValue("TestID", TestID)
        tCookie.Expires = DateAdd(DateInterval.Minute, 20, Now)
        tCookie.Domain = request.RequestUri.Host
        tCookie.Path = "/"

        Dim Cookies As IEnumerable(Of CookieHeaderValue) = New CookieHeaderValue() {New CookieHeaderValue("TestID", TestID)}

        response.Headers.AddCookies(Cookies)

        '把response繼續往前傳
        Return response

    End Function

    ''' <summary>
    ''' 取得Cookie
    ''' </summary>
    ''' <param name="request">Request</param>
    ''' <param name="CookieName">Cookie的名字</param>
    ''' <returns></returns>
    Public Function getCookie(ByVal request As HttpRequestMessage, ByVal CookieName As String) As String
        Dim Rc As String = ""
        Dim cookie As CookieHeaderValue = request.Headers.GetCookies(CookieName).FirstOrDefault()
        If cookie IsNot Nothing Then
            Rc = cookie(CookieName).Value
        End If
        Return Rc
    End Function
End Class

 

Global.asax 註冊 MessageHandler

接著,把剛剛的 MessageHandler 註冊到 Global.asax中

Imports System.Web.Http
Imports System.Web.Optimization

Public Class WebApiApplication
    Inherits System.Web.HttpApplication

    ''' <summary>
    ''' 掛載Message Handler
    ''' </summary>
    ''' <param name="config"></param>
    ''' <remarks></remarks>
    Shared Sub Configure(config As HttpConfiguration)
        '這裡可以設定要掛載多組Message Handler
        config.MessageHandlers.Add(New TestMessageHandler())
    End Sub

    Protected Sub Application_Start()
        '在Application_Start事件,呼叫寫的Sub掛上
        Configure(GlobalConfiguration.Configuration)

        AreaRegistration.RegisterAllAreas()
        GlobalConfiguration.Configure(AddressOf WebApiConfig.Register)
        FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters)
        RouteConfig.RegisterRoutes(RouteTable.Routes)
        BundleConfig.RegisterBundles(BundleTable.Bundles)
    End Sub
End Class

參考資料

Example: Set and Retrieve Cookies in a Message Handler

 


以下是簽名:


Microsoft MVP
Visual Studio and Development Technologies
(2005~2019/6)