前提・実現したいこと
VBでhttpでファイル送信する機能を作っています。
.NET FrameworkのhttpClientを使用して実装しています。
httpリクエスト、レスポンスの内容をログ出力するために、
DelegatingHandlerをoverrideするクラスを作ったのですが、
MyBase.SendAsync(request, cancellationToken)を処理すると、
Catch へ処理が遷移して
"内部ハンドラーが割り当てられていません。"
というエラーになります。
対処方法がわからないので、教えていただきたいです。
該当のソースコード
VB.NET
1Imports System.Net.Http 2Imports System.Net.Http.Headers 3Imports System.Text 4Imports System.IO 5 6 7Module Module1 8 9 Sub Main() 10 11 Dim task As Task 12 task = HttpReq() 13 task.Wait() 14 15 End Sub 16 17 18 19 Async Function HttpReq() As Task 20 21 Try 22 23 Dim url As String = "https://example.com/" 24 Dim client As HttpClient 25 Dim content As MultipartFormDataContent 26 27 client = New HttpClient(New MyMessageHandler) 28 content = New MultipartFormDataContent() 29 30 'id 31 Dim sId As String = "AAA" 32 Dim sContent1 = New StringContent(sId) 33 sContent1.Headers.ContentType = Nothing 34 content.Add(sContent1, "id") 35 36 'file 37 Dim bFile As Byte() = System.IO.File.ReadAllBytes("c:\temp\test.dat") 38 Dim bContent = New ByteArrayContent(bFile) 39 content.Add(bContent) 40 41 bContent.Headers.ContentType = New MediaTypeHeaderValue("application/octet-stream") 42 bContent.Headers.ContentDisposition.Name = "file" 43 bContent.Headers.ContentDisposition.FileName = "test.dat" 44 45 Dim response As HttpResponseMessage 46 response = Await client.PostAsync(url, content) 47 48 Dim statusCd As String 49 statusCd = response.StatusCode 50 51 Dim reasonPhrase As String 52 reasonPhrase = response.ReasonPhrase 53 54 Catch ex As Exception 55 Dim err As String = ex.Message 56 57 End Try 58 59 End Function 60 61End Module 62 63 64Public Class MyMessageHandler 65 Inherits System.Net.Http.DelegatingHandler 66 67 Protected Overrides Function SendAsync(request As HttpRequestMessage, cancellationToken As Threading.CancellationToken) As Task(Of HttpResponseMessage) 68 'ログ出力処理を入れる 69 Return MyBase.SendAsync(request, cancellationToken) 70 'ログ出力処理を入れる 71 End Function 72 73End Class 74
試したこと
以下のようにハンドラMyMessageHandlerを使用しないようにするとエラーは発生しません。
'client = New HttpClient(New MyMessageHandler)
client = New HttpClient()
その他
VBでhttp通信の開発を行うのは初めてです。
httpリクエスト、応答をログ出力するのに他により良い方法があれば教えていただきたいです。
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2019/01/15 00:15 編集