ASP.NET_Webform進行Post傳送並接收來自泛型處裡函式的回傳

於某段事件中(在此用Button)執行HTTP POST 傳送

xxx.aspx
Code
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
 Protected Sub btnLoad_Click(sender As Object, e As EventArgs) _
        Handles btnLoad.Click
  
#Region "前期串資料"
  ' .....do something
#End Region
  
#Region "WEB POST Request"
  '在此用的是亂掰的URL 和目錄
  'http://192.168.87.87
  Dim strURL As String = Request.Url.Scheme & System.Uri.SchemeDelimiter & Request.Url.Host
  'http://192.168.87.87/AAA/BBB/CCC/
  strURL &= "/AAA/BBB/CCC/"
  'http://192.168.87.87/AAA/BBB/CCC/xxx.ashx
  strURL &= "xxx.ashx"
  
  Dim myRequest As WebRequest = WebRequest.Create(strURL)
        myRequest.Method = "POST"
  
  '傳送過程中有包含一些中文內容欄位會特別做Encode
        Dim dstEncoding As Encoding = Encoding.GetEncoding("gb2312")
        Dim postData As String = String.Format("Currency={0}&CusIDCompany={1}&CusOrdNo={2}&Master={3}&SalesMan={4}&FinalCustomer={5}&NewBillNo={6}&lport={7}&FinalAddress={8}&OrdNoTw={9}&ShInvoiceNo={10}&ContractNo={11}",
                                               HttpUtility.UrlEncode(res_currency, dstEncoding),  '美金
                                               cus_id,
                                               cus_ord_no,
                                               master,
                                               salesman,
                                               final_customer,
                                               new_bill_no,
                                               lport,
                                               final_address,
                                               ord_no_tw,
                                               sh_invoice_no,
                                               lading_no)
  Dim byteArr() As Byte = Encoding.ASCII.GetBytes(postData)
        myRequest.ContentType = "application/x-www-form-urlencoded;charset=gb2312"
        myRequest.ContentLength = byteArr.Length
        Using dataStream As Stream = myRequest.GetRequestStream()
            dataStream.Write(byteArr, 0, byteArr.Length)
        End Using
  
  Dim dicData As New Dictionary(Of String, String)
        Try
            Using myResponse As WebResponse = myRequest.GetResponse()
                Using streamDataResponse As Stream = myResponse.GetResponseStream()
                    Using streamReader As New StreamReader(streamDataResponse)
                        Dim strRespFromServ As String = streamReader.ReadToEnd()
                        If Not String.IsNullOrEmpty(strRespFromServ) Then
                            Dim lsKey As List(Of String) = {"Currency"}.ToList()
                            For Each retItem In strRespFromServ.Split(";").Where(Function(item) Not String.IsNullOrEmpty(item)).ToList()
                                With retItem.Split("=").ToList()
                                    If lsKey.Contains(.Item(0)) Then
                                        dicData.Add(.Item(0), UnicodeToStr(.Item(1).Trim())) '有繁體、簡體中文內容的欄位
                                    Else
                                        dicData.Add(.Item(0), .Item(1).Trim())
                                    End If
                                End With
                            Next
                        End If
                    End Using
                End Using
            End Using
        Catch ex As Exception
            Response.Write("Response Exception:" & ex.ToString() & "<br>")
            Response.Write("Response Exception Call Stack:" & ex.StackTrace & "<br>")
            Debug.Print(ex.ToString())
        End Try
#End Region
  
#Region "控件或變數的賦值"
  dicData.Item("xxxx")
  
#End Region
 End Sub  
  

xxx.ashx

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
Imports System.Web
Imports System.Web.Services

Public Class XXXHandler
    Implements System.Web.IHttpHandler, IRequiresSessionState
 
 
   Sub ProcessRequest(ByVal context As HttpContext) Implements IHttpHandler.ProcessRequest
  context.Response.ContentType = "text/plain"
  Dim dicContext As New Dictionary(Of String, String)
        If Not String.IsNullOrEmpty(strContext) Then
            For Each itemCon In strContext.Split("&").ToList()
                With itemCon.Split("=").ToList()
                    dicContext.Add(.Item(0), .Item(1)) '%c3%c0%bd%f0
                End With
            Next
        End If
  
  
        Try
            'Dim strCurrency As String = HttpUtility.UrlDecode(Convert.ToString(context.Request.Form("Currency")), Encoding.GetEncoding("gb2312"))
            Dim strCurrency As String = StrToUnicode(HttpUtility.UrlDecode(Convert.ToString(dicContext.Item("Currency")), Encoding.GetEncoding("gb2312")))
   '美金->GB2312: %c3%c0%bd%f0
   'dicContext.Item("Currency")=>'%c3%c0%bd%f0
   'HttpUtility.UrlDecode(dicContext.Item("Currency"), Encoding.GetEncoding("gb2312"))=>美金 (但是網頁顯示可能會看到??亂碼,因此轉成unicode,於回傳到接收端後透過unicode轉成對應簡繁中文字)
   'StrToUnicode(HttpUtility.UrlDecode(dicContext.Item("Currency"), Encoding.GetEncoding("gb2312")))=\u7F8E\u91D1

            Dim strCusIDCompany As String = Convert.ToString(context.Request.Form("CusIDCompany"))
            Dim strCusOrdNo As String = Convert.ToString(context.Request.Form("CusOrdNo"))
            Dim strMaster As String = Convert.ToString(context.Request.Form("Master"))
            Dim strSalesMan As String = Convert.ToString(context.Request.Form("SalesMan"))
            Dim strFinalCustomer As String = Convert.ToString(context.Request.Form("FinalCustomer"))
            Dim strFinalAddress As String = Convert.ToString(context.Request.Form("FinalAddress"))
            Dim strNewBillNo As String = Convert.ToString(context.Request.Form("NewBillNo"))
            Dim strlport As String = Convert.ToString(context.Request.Form("lport"))
            Dim strOrdNoTw As String = Convert.ToString(context.Request.Form("OrdNoTw"))
            Dim strShInvoiceNo As String = Convert.ToString(context.Request.Form("ShInvoiceNo"))
            Dim strLadingNo As String = Convert.ToString(context.Request.Form("LadingNo"))

            

            context.Response.Write("Currency=" & strCurrency & ";")

            context.Response.Write("CusIDCompany=" & strCusIDCompany & ";")
            context.Response.Write("lport=" & strlport & ";")
            context.Response.Write("PackYear=" & l_year & ";")
            context.Response.Write("PackMonth=" & l_month & ";")
            context.Response.Write("PackDay=" & l_day & ";")
            context.Response.Write("LadingNo=" & strLadingNo & ";")
            context.Response.Write("NewBillNo=" & strNewBillNo & ";")
            context.Response.Write("ShFlag=" & new_sh_flag & ";")
            context.Response.Write("OrderNoTw=" & strOrdNoTw & ";")
            context.Response.Write("InvoiceNoTw=" & tw_invoice_no & ";")
            context.Response.Write("CusName=" & strCusIDCompany & ";")
            context.Response.Write("Master=" & strMaster & ";")
            context.Response.Write("Salesman=" & strSalesMan & ";")
            context.Response.Write("CusOrdNo=" & strCusOrdNo & ";")
            context.Response.Write("FinalCustomer=" & strFinalCustomer & ";")
            context.Response.Write("m_flag=" & m_flag & ";")
            context.Response.Write("tw_ord_no=" & tw_ord_no & ";")
            context.Response.Write("tw_type_id=" & tw_type_id & ";")
            context.Response.Write("tw_item_id=" & tw_item_id & ";")

        Catch ex As Exception
            context.Response.Write("ASHX Exception:" & ex.ToString() & "<br>")
            context.Response.Write("ASHX Exception call stack:" & ex.StackTrace & "<br>")
        End Try  
    End Sub
 
    Private Shared Function GetStringFromInputStream(context As HttpContext) As String
        Dim strData As String = ""
        Using reader As New IO.StreamReader(context.Request.InputStream)
            strData = reader.ReadToEnd()
        End Using
        Return strData
    End Function
 
    ReadOnly Property IsReusable() As Boolean Implements IHttpHandler.IsReusable
        Get
            Return False
        End Get
    End Property
 
End Class 


Reference:

如何在 .aspx 將資料 post 到 .ashx
http://readily-notes.blogspot.com/2013/09/aspx-post-ashx.html
'[轉貼] 在Server端Post資料到.ashx
https://coolong124220.nidbox.com/diary/read/8045492
'.NET ASP.NET一般处理程序(HttpHandler)
https://blog.csdn.net/qq_43434300/article/details/89604958
C# 字符编码解码 Encoder 和Decoder
https://www.cnblogs.com/2Yous/p/5801349.html
Debugging an HTTP Handler (*.ashx) in ASP.NET 2.0
https://www.codeguru.com/csharp/.net/net_debugging/article.php/c19547/Debugging-an-HTTP-Handler-ashx-in-ASPNET-20.htm
How to set in Visual Studio Startup Page in web config
https://forums.asp.net/t/1934284.aspx?How+to+set+in+Visual+Studio+Startup+Page+in+web+config+

留言

這個網誌中的熱門文章

何謂淨重(Net Weight)、皮重(Tare Weight)與毛重(Gross Weight)

Architecture(架構) 和 Framework(框架) 有何不同?_軟體設計前的事前規劃的藍圖概念

(2021年度)駕訓學科筆試準備題庫歸納分析_法規是非題