<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Kestrel 彙整 - 泰克哪裡去</title>
	<atom:link href="https://tech.uccu.website/tag/kestrel/feed" rel="self" type="application/rss+xml" />
	<link>https://tech.uccu.website/tag/kestrel</link>
	<description>一個科技相關的隨手記錄網站</description>
	<lastBuildDate>Sat, 17 Sep 2022 20:51:26 +0000</lastBuildDate>
	<language>zh-TW</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=6.8.1</generator>
<site xmlns="com-wordpress:feed-additions:1">119574712</site>	<item>
		<title>Asp.Net Core Kestrel設定Request Body Size</title>
		<link>https://tech.uccu.website/asp-net-core-kestrel-set-max-request-body-size.html?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=asp-net-core-kestrel-set-max-request-body-size</link>
					<comments>https://tech.uccu.website/asp-net-core-kestrel-set-max-request-body-size.html#respond</comments>
		
		<dc:creator><![CDATA[鳴人]]></dc:creator>
		<pubDate>Thu, 17 Feb 2022 08:58:53 +0000</pubDate>
				<category><![CDATA[.Net]]></category>
		<category><![CDATA[程式設計]]></category>
		<category><![CDATA[asp.net core]]></category>
		<category><![CDATA[Kestrel]]></category>
		<guid isPermaLink="false">https://tech.uccu.website/?p=1673</guid>

					<description><![CDATA[<p>前兩天同事利用Web Api Post上傳檔案碰到了Request body too large的問題，我想到 ... <a title="Asp.Net Core Kestrel設定Request Body Size" class="read-more" href="https://tech.uccu.website/asp-net-core-kestrel-set-max-request-body-size.html" aria-label="Read more about Asp.Net Core Kestrel設定Request Body Size">閱讀全文</a></p>
<p>這篇文章 <a href="https://tech.uccu.website/asp-net-core-kestrel-set-max-request-body-size.html">Asp.Net Core Kestrel設定Request Body Size</a> 最早出現於 <a href="https://tech.uccu.website">泰克哪裡去</a>。</p>
]]></description>
										<content:encoded><![CDATA[
<p>前兩天同事利用Web Api Post上傳檔案碰到了Request body too large的問題，我想到過去的經驗就是因為預設值比較小，所以改一下設定應該就可以Work了。</p>



<blockquote class="wp-block-quote is-layout-flow wp-block-quote-is-layout-flow"><p>Request body too large</p><cite>Microsoft.AspNetCore.Server.Kestrel.Core.BadHttpRequestException: Request body too large.<br>at Microsoft.AspNetCore.Server.Kestrel.Core.BadHttpRequestException.Throw(RequestRejectionReason reason)<br>at Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http.Http1ContentLengthMessageBody.OnReadStarting()<br>at Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http.MessageBody.TryStart()<br>at Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http.MessageBody.ConsumeAsync()<br>at Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http.HttpProtocol.ProcessRequests[TContext](IHttpApplication<code>1 application) at Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http.HttpProtocol.ProcessRequestsAsync[TContext](IHttpApplication</code>1 application)</cite></blockquote>



<p>通常不會把每一個設定值都記在腦中，所以就搜尋了一下Kestrel Server的設定應該在appsettings.json檔案中如何調整，查到了<a href="https://docs.microsoft.com/en-us/aspnet/core/fundamentals/servers/kestrel/options?view=aspnetcore-6.0" target="_blank" rel="noreferrer noopener">設定MaxRequestBodySize的C#程式碼</a>，但是翻了很多篇網路上的文章都沒有找到如何在設定檔裡面調整的方法…</p>



<span id="more-1673"></span>



<p>從官方文件和一些文章中看到下面的json設定內容，所以推斷應該同樣在Limits底下加上MaxRequestBodySize和設定值就可以搞定，結果實際上試了之後發現竟然完全沒效…，<a href="https://github.com/aspnet/Announcements/issues/267" target="_blank" rel="noreferrer noopener">雖然是有看到有些設定在Server啟動之後會變成唯讀的情況</a>，之後修改的內容不會更新，不過我一直覺得加在appsettings.json裡面不就是在啟動的時候會載入的設定？</p>



<pre class="wp-block-prismatic-blocks"><code class="language-">{
  &quot;Kestrel&quot;: {
    &quot;Limits&quot;: {
      &quot;MaxConcurrentConnections&quot;: 100,
      &quot;MaxConcurrentUpgradedConnections&quot;: 100
    },
    &quot;DisableStringReuse&quot;: true
  }
}</code></pre>



<p>從這裡的文件內容則是看到下面這麼一段話…，因為Limits的設定是在KestrelServerOptions底下，所以我一直認為應該是可以透過appsettings.json設定，無奈試了幾次之後都沒辦法正常，所以最後只好妥協認命的去改Code&#8230;</p>



<blockquote class="wp-block-quote is-layout-flow wp-block-quote-is-layout-flow"><p></p><cite>Microsoft.AspNetCore.Server.Kestrel.Core.KestrelServerOptions and endpoint configuration are configurable from configuration providers. Set other Kestrel configuration in C# code.</cite></blockquote>



<p>其實程式碼也不難，作法是在KestrelServerOptions的Limit底下的MaxRequestBodySize設定大小，因為是nullable型態，所以也可以設定為null。</p>



<p>第一段的是官方文件中的程式碼，第二段則是我寫在ConsoleApp(Program.cs)裡的程式碼，在UseKestrel的Extension method中設定。<br>因為是跑在Container裡面的程式，在改Code之前已經在shell script中判斷是否有MAX_REQ_BODY_SIZE這個環境變數來調整appsettings.json的檔案內容，所以是透過判斷是否有MAX_REQ_BODY_SIZE這個環境變數來設定大小，如果沒有找到MAX_REQ_BODY_SIZE就設定100MB的預設值，比官方預設不到30MB的大小再大一些。</p>



<pre class="wp-block-prismatic-blocks"><code class="language-csharp">builder.WebHost.ConfigureKestrel(serverOptions =&gt;
{
    serverOptions.Limits.MaxRequestBodySize = 100_000_000;
});</code></pre>



<pre class="wp-block-prismatic-blocks"><code class="language-csharp">public static IHostBuilder CreateHostBuilder(string[] args)
{
    return Host.CreateDefaultBuilder(args)
               .ConfigureWebHostDefaults(webBuilder =&gt;
                {
                    webBuilder.UseKestrel(opt =&gt;
                        {
                            long maxReqBodySize = 100 * 1024 * 1024;
                            if (Environment.GetEnvironmentVariable(&quot;MAX_REQ_BODY_SIZE&quot;) != null)
                            {
                                long.TryParse(Environment.GetEnvironmentVariable(&quot;MAX_REQ_BODY_SIZE&quot;), out maxReqBodySize);
                            }
                            opt.Limits.MaxRequestBodySize = maxReqBodySize;
                        })
                        .UseStartup&lt;Startup&gt;();
                });
}</code></pre>



<p>結果最後繞一圈多花了一天的時間還是乖乖的改了程式碼…</p>



<p>對了，上面這樣的作法是整個網站都設定相同大小的限制，或許會有一些其它額外的潛在風險，所以官方建議的作法是只在需要調整的Function加上<a href="https://docs.microsoft.com/en-us/aspnet/core/fundamentals/servers/kestrel/options?view=aspnetcore-6.0#maximum-request-body-size" target="_blank" rel="noreferrer noopener">RequestSizeLimit Attribute</a>。</p>



<p>參考資訊：</p>



<ul class="wp-block-list"><li><a href="https://thecodeblogger.com/2021/05/07/certificates-and-limits-for-asp-net-core-kestrel-web-server/">The Code Blogger &#8211; Certificates and Limits for ASP .NET Core Kestrel Web Server</a></li><li><a href="https://github.com/dotnet/AspNetCore.Docs/blob/main/aspnetcore/fundamentals/servers/kestrel/options.md">AspNetCore.Docs/options.md at main · dotnet/AspNetCore.Docs · GitHub</a></li><li><a href="https://docs.microsoft.com/en-us/aspnet/core/mvc/models/file-uploads?view=aspnetcore-6.0#unexpected-not-found-error-with-iis">Upload files in ASP.NET Core | Microsoft Docs</a></li><li><a href="https://www.talkingdotnet.com/how-to-increase-file-upload-size-asp-net-core/">How to increase file upload size in ASP.NET Core (talkingdotnet.com)</a></li><li><a href="https://www.aspsnippets.com/Articles/Set-MaxRequestLength-in-ASPNet-Core.aspx">Set MaxRequestLength in ASP.Net Core (aspsnippets.com)</a></li><li><a href="https://khalidabuhakmeh.com/increase-file-upload-limit-for-aspdotnet">Increase ASP.NET File Upload Limits | Khalid Abuhakmeh</a></li><li><a href="https://github.com/aspnet/Announcements/issues/267">New default 30 MB (~28.6 MiB) max request body size limit · Issue #267 · aspnet/Announcements · GitHub</a></li><li><a href="https://stackoverflow.com/questions/38698350/increase-upload-file-size-in-asp-net-core">c# &#8211; Increase upload file size in Asp.Net core &#8211; Stack Overflow</a></li><li><a href="https://docs.microsoft.com/en-us/aspnet/core/fundamentals/servers/kestrel/options?view=aspnetcore-6.0">Configure options for the ASP.NET Core Kestrel web server | Microsoft Docs</a></li><li><a href="https://stackoverflow.com/questions/46738364/increase-upload-request-length-limit-in-kestrel/46738667">asp.net core &#8211; Increase upload request length limit in Kestrel &#8211; Stack Overflow</a></li></ul>
<p>這篇文章 <a href="https://tech.uccu.website/asp-net-core-kestrel-set-max-request-body-size.html">Asp.Net Core Kestrel設定Request Body Size</a> 最早出現於 <a href="https://tech.uccu.website">泰克哪裡去</a>。</p>
]]></content:encoded>
					
					<wfw:commentRss>https://tech.uccu.website/asp-net-core-kestrel-set-max-request-body-size.html/feed</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">1673</post-id>	</item>
		<item>
		<title>Asp.Net Core Kestrel Server關閉Request Info記錄</title>
		<link>https://tech.uccu.website/trun-off-kestrel-web-request-info.html?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=trun-off-kestrel-web-request-info</link>
					<comments>https://tech.uccu.website/trun-off-kestrel-web-request-info.html#respond</comments>
		
		<dc:creator><![CDATA[鳴人]]></dc:creator>
		<pubDate>Fri, 28 Jan 2022 02:45:21 +0000</pubDate>
				<category><![CDATA[.Net]]></category>
		<category><![CDATA[Kestrel]]></category>
		<guid isPermaLink="false">https://tech.uccu.website/?p=1642</guid>

					<description><![CDATA[<p>今天同事詢問是否有辦法停用Kestrel的http trace/track，我第一個想到的是執行時會顯示的Re ... <a title="Asp.Net Core Kestrel Server關閉Request Info記錄" class="read-more" href="https://tech.uccu.website/trun-off-kestrel-web-request-info.html" aria-label="Read more about Asp.Net Core Kestrel Server關閉Request Info記錄">閱讀全文</a></p>
<p>這篇文章 <a href="https://tech.uccu.website/trun-off-kestrel-web-request-info.html">Asp.Net Core Kestrel Server關閉Request Info記錄</a> 最早出現於 <a href="https://tech.uccu.website">泰克哪裡去</a>。</p>
]]></description>
										<content:encoded><![CDATA[
<p>今天同事詢問是否有辦法停用Kestrel的http trace/track，我第一個想到的是執行時會顯示的Request Info記錄(如下圖)，一直在執行的時候沒特別設定時，會在Web Request進來的時候記錄相關資訊，就會有一堆的訊息一直往上跑…</p>


<div class="wp-block-image">
<figure class="aligncenter size-full"><img data-recalc-dims="1" decoding="async" width="677" height="50" src="https://i0.wp.com/storage.googleapis.com/stateless-tech-uccu-website/2022/01/d39c6caf-image.png?resize=677%2C50&#038;ssl=1" alt="" class="wp-image-1645" srcset="https://i0.wp.com/storage.googleapis.com/stateless-tech-uccu-website/2022/01/d39c6caf-image.png?w=677&amp;ssl=1 677w, https://i0.wp.com/storage.googleapis.com/stateless-tech-uccu-website/2022/01/d39c6caf-image.png?resize=300%2C22&amp;ssl=1 300w" sizes="(max-width: 677px) 100vw, 677px" /><figcaption>Kestrel Web Request Info</figcaption></figure></div>


<p>如果要關閉上面這些Request Info記錄的顯示，在appsettings.json檔案中加上Logging的記錄就可以了，參考下面的這段設定內容：</p>



<pre class="wp-block-prismatic-blocks"><code class="language-json">&quot;Logging&quot;: {
    &quot;LogLevel&quot;: {
      &quot;Default&quot;: &quot;Error&quot;,
      &quot;Microsoft.Hosting&quot;: &quot;Warning&quot;
    }
  }</code></pre>



<p>加到appsettings.json檔案之後重新啟動程式再試試，頁面正常顯示卻不會有這些Request Info洗版了。</p>



<p>參考資訊：</p>



<p><a href="https://docs.microsoft.com/zh-tw/aspnet/core/fundamentals/logging/?view=aspnetcore-6.0#configure-logging">https://docs.microsoft.com/zh-tw/aspnet/core/fundamentals/logging/?view=aspnetcore-6.0#configure-logging</a></p>
<p>這篇文章 <a href="https://tech.uccu.website/trun-off-kestrel-web-request-info.html">Asp.Net Core Kestrel Server關閉Request Info記錄</a> 最早出現於 <a href="https://tech.uccu.website">泰克哪裡去</a>。</p>
]]></content:encoded>
					
					<wfw:commentRss>https://tech.uccu.website/trun-off-kestrel-web-request-info.html/feed</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">1642</post-id>	</item>
	</channel>
</rss>
