2025年8月29日 星期五

ASP.NET System.Threading.ThreadAbortException: 執行緒已經中止

 參考引用來源:ASP.NET System.Threading.ThreadAbortException: 執行緒已經中止
---

發生錯誤:執行緒已經中止。     

於 System.Threading.Thread.AbortInternal()

於 System.Threading.Thread.Abort(Object stateInfo)

於 System.Web.HttpResponse.AbortCurrentThread()

於 System.Web.HttpResponse.Redirect(String url, Boolean endResponse, Boolean permanent)

---


解決方案:https://support.microsoft.com/zh-tw/kb/918181

<%@ Page Language="C#" Async="true"%>


當 HttpResponse.Redirect 方法 endResponse 參數不設為 false 時,就會發生這個問題。 根據預設值,endResponse 參數設定為 true。



轉貼連結:http://www.dotblogs.com.tw/boei/archive/2010/07/11/16485.aspx

將網頁轉出成word的時候,最後會來個Response.End()來結束它的輸出,但都會發生<System.Threading.ThreadAbortException> 執行緒已經中止,雖然不會造成系統上的什麼問題。

解決方法:

1.    繼續用Response.End(),外面用try – catch包住,但try – catch會比較消耗資源,所以不考慮。

2.    改用HttpContext.Current.ApplicationInstance.CompleteRequest(),可以跳過Application_EndRequest 事件的執行。

 

如果使用Response.Redirect 或 Server.Transfer 方法也發生一樣狀況的話,就可以使用Response.Redirect(String url, bool endResponse),endResponse就設為False,因為Response.Redirect內部會用到Response.End(),設為False就是要停用Response.End()方法。



2025年8月26日 星期二

webclient 無法建立 SSL/TLS 的安全通道

 在 framework 4.0 無法建立 tls12

只能自己新增:

in .net Framework 4.0 add

ServicePointManager.SecurityProtocol = (SecurityProtocolType)3072; //TLS 1.2

2025年8月25日 星期一

ASP.NET C# URL 網址參數解析,取得網址參數

引用來源:ASP.NET C# URL 網址參數解析,取得網址參數 


  1.  底下分別列出解屬性及解析結果
參數結果
Request.ApplicationPath/
Request.Url.Hostmy.url.com
Request.Url.Port8080
Request.Url.Schemehttps
Request.Url.Authoritymy.url.com:8080
Request.Path/Detail/Page/List.aspx/showmore
Request.Url.LocalPath/Detail/Page/List.aspx/showmore
Request.PathInfo/showmore
Request.Url.Query?mid=20
Request.CurrentExecutionFilePath/Detail/Page/List.aspx
Request.FilePath/Detail/Page/List.aspx
Request.RawUrl/Detail/Page/List.aspx/showmore?mid=20
Request.Url.PathAndQuery/Detail/Page/List.aspx/showmore?mid=20
Request.Url.AbsoluteUrihttps://my.url.com:8080/Detail/Page/List.aspx/showmore?mid=20
Request.Url.AbsolutePath/Detail/Page/List.aspx/showmore

  1.  取得系統路徑
參數結果
Request.PhysicalPathC:\wwwroot\Detail\Page\List.aspx
System.IO.Path.GetDirectoryName(Request.PhysicalPath)C:\wwwroot\Detail\Page
Request.PhysicalApplicationPathC:\wwwroot\
System.IO.Path.GetFileName(Request.PhysicalPath)List.aspx

  1.  解析參數
參數結果
Request.Url.Segments/, Detail/, Page/, List.aspx/, showmore


2025年8月23日 星期六

跳轉頁面發生 RegisterForEventValidation 只能在 Render(); 期間呼叫

 跳轉頁面發生:

System.InvalidOperationException: 'RegisterForEventValidation 只能在 Render(); 期間呼叫'

這個問題,可以設定aspx原始檔中<%Page%>的以下兩個設定解決

EnableEventValidation = "false" AutoEventWireup="true"



2025年8月21日 星期四

windows 11 pdf 小圖示不見

 一、在C:\Users\ABC\AppData\Local的路徑下的IconCache.db刪除(其中ABC為你自己設定的使用者名稱)

二、然後在工作管理員中將「Windows檔案總管」重新啟動,或是重新開機即可恢復


2025年8月20日 星期三

Java to C# Converter

 微軟:Java to C# Converter free

---

還有各種轉換,有需要的可看看 探索更多



確認 applicationhost.config 或 web.config 檔案中的requestLimits@maxQueryString 設定

 mvc中查询字符串请求过长

---

底下方法還是不行!

發生錯誤:執行緒已經中止。

看來是須要改寫方法了...(無法偷懶...)



---

引用記錄一下:

在项目的web.config里,<system.webServer>路径下添加如下配置:


<security>  

      <requestFiltering>  

      <requestLimits maxQueryString="4080" />  

      </requestFiltering>  

</security> 


打开项目中的Web.config,在<system.web>节点下设置httpRuntime节点的maxQueryStringLength属性,Web.config中的设置如下:


<system.web>

    <httpRuntime maxQueryStringLength="9999"/>

</system.web>

------------




2025年8月18日 星期一

MSSQL DATALENGTH 尾端空白字串


select '0022000114693',len('0022000114693'),len('0022000114693 '),DATALENGTH('0022000114693'),DATALENGTH('0022000114693 ')


值變化:



2025年8月12日 星期二

Setup POST REST Webservice with ASP.net and VB.net

 Setup POST REST Webservice with ASP.net and VB.net

Add new REST Service into existing ASP.net web application

---


JSON HTTP POST Request In Visual Basic .NET

 JSON HTTP POST Request In Visual Basic .NET

---

引用來源:

'Install Newtonsoft.json
'-----------------------
'
'PM> Install-Package Newtonsoft.Json -Version 6.0.8

'Sample Usage
'------------

'Dim jsonPost As New JsonPost("http://192.168.254.104:8000")
'Dim dictData As New Dictionary(Of String, Object)
'dictData.Add("test_key", "test_value")
'jsonPost.postData(dictData)

Imports Newtonsoft.Json
Imports System.Net
Imports System.Text
Public Class JsonPost

    Private urlToPost As String = ""

    Public Sub New(ByVal urlToPost As String)
        Me.urlToPost = urlToPost
    End Sub

    Public Function postData(ByVal dictData As Dictionary(Of String, Object)) As Boolean
        Dim webClient As New WebClient()
        Dim resByte As Byte()
        Dim resString As String
        Dim reqString() As Byte

        Try
            webClient.Headers("content-type") = "application/json"
            reqString = Encoding.Default.GetBytes(JsonConvert.SerializeObject(dictData, Formatting.Indented))
            resByte = webClient.UploadData(Me.urlToPost, "post", reqString)
            resString = Encoding.Default.GetString(resByte)
            Console.WriteLine(resString)
            webClient.Dispose()
            Return True
        Catch ex As Exception
            Console.WriteLine(ex.Message)
        End Try
        Return False
    End Function

End Class

Making a post request with data in vb.net

 Making a post request with data in vb.net

---

引用來源:

Dim postdata As New JObject

            postdata.Add("service_id", "value 1")

            postdata.Add("template_id", "Value 2")

            postdata.Add("user_id", "Value 3")

            'postdata contains data which will be posted with the request

            Dim finalString as String = postdata.ToString



            Dim httpWebRequest = CType(WebRequest.Create("Api address Here"), HttpWebRequest)

            httpWebRequest.ContentType = "application/json"

            httpWebRequest.Method = "POST"


            Using streamWriter = New StreamWriter(httpWebRequest.GetRequestStream())

                streamWriter.Write(finalString)

            End Using


            Dim httpResponse = CType(httpWebRequest.GetResponse(), HttpWebResponse)


            Using streamReader = New StreamReader(httpResponse.GetResponseStream())

                Dim responseText as String = streamReader.ReadToEnd() 

                'responseText contains the response received by the request               

            End Using

Here the data format is:


{

    service_id: 'YOUR_SERVICE_ID',

    template_id: 'YOUR_TEMPLATE_ID',

    user_id: 'YOUR_USER_ID'

}


VB.NET REST API call with Basic Authorization

 VB.NET REST API call with Basic Authorization

---

引用來源:

Dim origResponse As HttpWebResponse

        Dim objResponse As HttpWebResponse

        Dim origReader As StreamReader

        Dim objReader As StreamReader


        Dim origRequest As HttpWebRequest = DirectCast(HttpWebRequest.Create("https://api.orls.voxeo.net/files/exports/2017/10/31?"), HttpWebRequest)

        origRequest.Headers.Add("Authorization", "Basic c3NhX2RzdDpBc3AzY3RfMTIzNA==")

        origRequest.AllowAutoRedirect = False

        origRequest.Method = "GET"

        Try

            origResponse = DirectCast(origRequest.GetResponse(), HttpWebResponse)

            Dim Stream As Stream = origResponse.GetResponseStream()

            Dim sr As New StreamReader(Stream, Encoding.GetEncoding("utf-8"))

            Dim str As String = sr.ReadToEnd()

            MessageBox.Show(str)

        Catch ex As WebException

            MsgBox(ex.Status)

            Dim myRequest As HttpWebRequest = DirectCast(HttpWebRequest.Create("https://api.orls.voxeo.net/files/exports/2017/10/31/Export-production-202715_20171030.zip.gpg"), HttpWebRequest)

            myRequest.Headers.Add("Authorization", "Basic c3NhX2RzdDpBc3AzY3RfMTIzNA==")

            Try

                objResponse = DirectCast(myRequest.GetResponse(), HttpWebResponse)


            Catch ex2 As WebException

                objReader = New StreamReader(objResponse.GetResponseStream())

                MsgBox(objReader.ReadToEnd())

                MsgBox(ex2.Status)

            End Try

        End Try


Calling REST API from Visual Basic

 Calling REST API from Visual Basic

---

引用來源:


Public Sub Try01(URL)

        Try

            Dim myReq As HttpWebRequest

            Dim myResp As HttpWebResponse

            Dim myReader As StreamReader

            myReq = HttpWebRequest.Create(URL)

            myReq.Method = "POST"

            myReq.ContentType = "application/json"

            myReq.Accept = "application/json"

            myReq.Headers.Add("Authorization", "Bearer LKJLMLKJLHLMKLJLM839800K=")

            Dim myData As String = "{""riskLevelStatus"":""0001"",""userId"":""10000004030"",""applicationName"":""MyTestRESTAPI""}"

            myReq.GetRequestStream.Write(System.Text.Encoding.UTF8.GetBytes(myData), 0, System.Text.Encoding.UTF8.GetBytes(myData).Count)

            myResp = myReq.GetResponse

            myReader = New System.IO.StreamReader(myResp.GetResponseStream)

            TextBox1.Text = myReader.ReadToEnd

        Catch ex As Exception

            TextBox1.Text = TextBox1.Text & "Error: " & ex.Message

        End Try

    End Sub


VB.NET || How To Send, Post & Process A REST API Web Request Using VB.NET

 VB.NET || How To Send, Post & Process A REST API Web Request Using VB.NET

---

很棒的code


ShareFileV3Sample

 ShareFileV3Sample

----

請參考來源:程式碼



2025年8月10日 星期日

vs 2022 webform BC30451: Name '' is not declared

 微軟:BC30451: Name '<name>' is not declared

看官網還是看不懂...是什麼問題!

----

參考:錯誤訊息1:BC30451名稱<xxx控制項>未宣告

看了這篇,有些懂了! 是複製造成的!? 

也不全然這樣的問題造成 BC30451

同1支code  ,  A PC Error   但 B PC 卻 OK  

我還在找差異性到底是在哪?

自從開發 webform + web api restful  for framework  就都感覺全不順

單純的 .Net Core 較順...

---------

20250811:

將 B PC OK 的專案(經過更動+儲存)改到 A PC 也OK了...

所以這個 BC30451: Name '<name>' is not declared

應該是無解了...



2025年8月6日 星期三

未將物件參考設定為物件的執行個體

引用來源: [C#]未將物件參考設定為物件的執行個體-個人經驗

[C#]未將物件參考設定為物件的執行個體-個人經驗

 當出現此訊息,標準說明網路很多"物件尚未實體化就呼叫它的屬性或方法",

以下為自己遇到的以及處理方式,作為紀錄

表示有設定的物件,可能是DataTable、Int、String、陣列、object等等,未設定值(沒有值),就直接使用

1.一般的

EX

DataTable dt = null ;

Q_txtBNKNM.Text = dt.Rows[0]["BNKNM"].ToString(); \\這裡就會出錯

這種debug會直接斷在這裡,很好處理

--------------------------------------------------------------------------------

2. 比較難查的,通常是已經包在dll的程式,吐回來的訊息,不會說明斷哪裡

    a. 利用搜尋,查找相關的程式檔案(關鍵字是自己會用到datatable or 陣列等等名稱)

    b. 程式前後文,也有可能造成此問題,前半寫好,後段尚未完成,但只想驗證前面時,也會            發生,會發生在有參數互相傳遞的程式間

 做為紀錄方便自己查詢




2025年8月5日 星期二

C# IIs 新增應用程式 web api

 c# Web API區域網IIS部署

https://medium.com/@misakaindex80/c-web-api%E5%8D%80%E5%9F%9F%E7%B6%B2iis%E9%83%A8%E7%BD%B2-82fe457aa966

(一)點選圖中"模組", 需要幫iis安裝運行API的模組(https://dotnet.microsoft.com/en-us/download/dotnet/3.1



[C#][ASP.NET] Web API 開發心得 (1) - WebForm 搭配 Web API

https://ithelp.ithome.com.tw/articles/10198037

ASP.NET Web API

 

使用 OWIN 自我裝載 ASP.NET Web API

https://learn.microsoft.com/zh-tw/aspnet/web-api/overview/hosting-aspnet-web-api/use-owin-to-self-host-web-api


自我託管 ASP.NET Web API 1 (C#)

https://learn.microsoft.com/zh-tw/aspnet/web-api/overview/older-versions/self-host-a-web-api


使用 ASP.NET Web API 建立 RESTful API

https://learn.microsoft.com/zh-tw/aspnet/web-api/overview/older-versions/build-restful-apis-with-aspnet-web-api



VBNET dataGridView當掉問題

 [C#] dataGridView當掉問題

private void InvokeGridViewAddRows(String str)

{

            if (this.InvokeRequired)

            {

                GridViewAddRows addRows = new GridViewAddRows((InvokeGridViewAddRows));

                this.Invoke(addRows, str);

            }

            else

            {

                    // 在這裡寫入原本取到str後要對dataGridView做的事

            }

}

--

我的問題是在 CellClick

程式調整:

Private Sub DGridV_CellClick(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles DGridV.CellClick

    Try

        If Me.InvokeRequired Then '加這一行即可防止整個form當掉

            If e.ColumnIndex = 0 Then

2025年8月3日 星期日

Windows Form 設計工具錯誤頁面

 官方:Windows Form 設計工具錯誤頁面

---

引用:

首先嘗試什麼

您通常可以透過清理並重建專案或解決方案來排除錯誤。

尋找 方案總管視窗。

在解決方案或專案上按右鍵,然後選取 [清除]。

在解決方案或專案上按右鍵,然後選取 [重建]。

----


*** 在 VS 2022 只要關掉[方案]再重新開啟方案 就可以正常了



 菜雞新訓記 (2): 認識 Api & 使用 .net Core 來建立簡單的 Web Api 服務吧