ASP.NET MVC, Url 라우팅 : 최대 경로 (URL) 길이
시나리오
좋은 오래된 쿼리 문자열 URL 구조를 사용하는 응용 프로그램이 있습니다.
?x=1&y=2&z=3&a=4&b=5&c=6
경로 구조로 변경했습니다.
/x/1/y/2/z/3/a/4/b/5/c/6
우리는 ASP.NET MVC와 (당연히) ASP.NET 라우팅을 사용하고 있습니다.
문제
문제는 매개 변수가 동적이며 수용해야하는 매개 변수의 양에 (이론적으로) 제한이 없다는 것입니다.
다음 열차에 치이기 전까지는 괜찮습니다.
HTTP 오류 400.0-잘못된 요청 ASP.NET이 URL에서 잘못된 문자를 감지했습니다.
IIS는 URL이 특정 길이를 초과하면이 오류를 발생시킵니다.
니티 그리 티
우리가 알아 낸 것은 다음과 같습니다.
이것은 IIS 문제가 아닙니다.
IIS에는 최대 경로 길이 제한이 있지만 위의 오류는 이것이 아닙니다.
Learn dot iis dot net 요청 필터링 섹션 사용 방법 "요청 제한에 따른 필터"
경로가 IIS에 비해 너무 길면 400.0이 아닌 404.14가 발생합니다.
또한 IIS 최대 경로 (및 쿼리) 길이를 구성 할 수 있습니다.
<requestLimits
maxAllowedContentLength="30000000"
maxUrl="260"
maxQueryString="25"
/>
이것은 ASP.NET 문제입니다.
주위를 둘러 본 후 :
IIS 포럼 스레드 : ASP.NET 2.0 최대 URL 길이? http://forums.iis.net/t/1105360.aspx
이것은 ASP.NET (실제로 .NET) 문제라는 것이 밝혀졌습니다.
문제의 핵심은 내가 알 수있는 한 ASP.NET은 260 자 이상의 경로를 처리 할 수 없다는 것입니다.
이것이 Phil the Haack 자신이 확인한 관의 못 :
스택 오버플로 ASP.NET URL MAX_PATH 제한 질문 ID 265251
질문
그래서 질문은 무엇입니까?
문제는 이것이 얼마나 큰 한계입니까?
내 앱의 경우 거래 킬러입니다. 대부분의 앱에서는 문제가되지 않을 수 있습니다.
공개는 어떻습니까? ASP.NET 라우팅이 언급 된 곳에서는이 제한에 대해 들어 본 적이 없습니다. ASP.NET MVC가 ASP.NET 라우팅을 사용한다는 사실은 이것의 영향을 더욱 크게 만듭니다.
어떻게 생각해?
나는 Mvc2 및 .Net Framework 4.0을 사용 하여이 문제를 해결하기 위해 web.config에서 다음을 사용했습니다.
<httpRuntime maxUrlLength="1000" relaxedUrlToFileSystemMapping="true" />
이를 해결하려면 다음과 같이하십시오.
프로젝트의 루트 web.config에서 system.web 노드 아래 :
<system.web>
<httpRuntime maxUrlLength="10999" maxQueryStringLength="2097151" />
...
또한 system.webServer 노드 아래에 추가해야하거나 긴 쿼리 문자열에 대한 보안 오류가 발생했습니다.
<system.webServer>
<security>
<requestFiltering>
<requestLimits maxUrl="10999" maxQueryString="2097151" />
</requestFiltering>
</security>
...
Http.sys 서비스는 Url 세그먼트 당 기본 최대 260 자로 코딩됩니다.
이 컨텍스트에서 "Url 세그먼트"는 Url에서 "/"문자 사이의 내용입니다. 예를 들면 :
http://www.example.com/segment-one/segment-two/segment-three
최대 허용 Url 세그먼트 길이는 레지스트리 설정으로 변경할 수 있습니다.
- 키:
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\services\HTTP\Parameters - 값:
UrlSegmentMaxLength - 유형 : REG_DWORD
- 데이터 : (원하는 새 URL 세그먼트 최대 허용 길이, 예 : 4096)
http.sys 설정에 대한 추가 정보 : http://support.microsoft.com/kb/820129
허용되는 최대 값은 32766입니다. 더 큰 값을 지정하면 무시됩니다. (크레딧 : Juan Mendes)
이 설정의 변경 사항을 적용하려면 PC를 다시 시작해야합니다. (크레딧 : David Rettenbacher, Juan Mendes)
좋아요, 제가 이것을 게시 한 이유 중 일부는 해결 방법을 찾았 기 때문이기도합니다.
나는 이것이 미래의 누군가에게 유용하기를 바랍니다. : D
해결 방법
해결 방법은 매우 간단하며 매우 좋습니다.
사이트의 어느 부분이 동적 매개 변수를 사용해야하는지 (따라서 동적 경로와 길이가 있음) 알기 때문에이 긴 URL을 ASP.NET에 도달하기 전에 가로 채어 ASP.NET 라우팅으로 보내는 것을 방지 할 수 있습니다.
Enter IIS7 Url Rewriting (or any equivalent rewrite module).
We set up a rule like this:
<rewrite>
<rules>
<rule>
<rule name="Remove Category Request Parameters From Url">
<match url="^category/(\d+)/{0,1}(.*)$" />
<action type="Rewrite" url="category/{R:1}" />
</rule>
</rules>
</rewrite>
Basically, what we're doing is just keeping enough of the path to be able to call the correct route downstream. The rest of the URL path we are hacking off.
Where does the rest of the URL go?
Well, when a rewrite rule is fired, the IIS7 URL Rewrite module automagically sets this header in the request:
HTTP_X_ORIGINAL_URL
Downstream, in the part of the app that parses the dynamic path, instead of looking at the path:
HttpContext.Request.Url.PathAndQuery
we look at that header instead:
HttpContext.Request.ServerVariables["HTTP_X_ORIGINAL_URL"]
Problem solved... almost!
The Snags
Accessing the Header
In case you need to know, to access the IIS7 Rewrite Module header, you can do so in two ways:
HttpContext.Request.ServerVariables["HTTP_X_ORIGINAL_URL"]
or
HttpContext.Request.Headers["X-ORIGINAL-URL"]
Fixing Relative Paths
What you will also notice is that, with the above setup, all relative paths break (URLs that were defined with a "~").
This includes URLs defined with the ASP.NET MVC HtmlHelper and UrlHelper methods (like Url.Route("Bla")).
This is where access to the ASP.NET MVC code is awesome.
In the System.Web.Mvc.PathHelper.GenerateClientUrlInternal() method, there is a check being made to see if the same URL Rewrite module header exists (see above):
// we only want to manipulate the path if URL rewriting is active, else we risk breaking the generated URL
NameValueCollection serverVars = httpContext.Request.ServerVariables;
bool urlRewriterIsEnabled = (serverVars != null && serverVars[_urlRewriterServerVar] != null);
if (!urlRewriterIsEnabled) {
return contentPath;
}
If it does, some work is done to preserve the originating URL.
In our case, since we are not using URL rewriting in the "normal" way, we want to short circuit this process.
We want to pretend like no URL rewriting happened, since we don't want relative paths to be considered in the context of the original URL.
The simplest hack that I could think of was to remove that server variable completely, so ASP.NET MVC would not find it:
protected void Application_BeginRequest()
{
string iis7UrlRewriteServerVariable = "HTTP_X_ORIGINAL_URL";
string headerValue = Request.ServerVariables[iis7UrlRewriteServerVariable];
if (String.IsNullOrEmpty(headerValue) == false)
{
Request.ServerVariables.Remove(iis7UrlRewriteServerVariable);
Context.Items.Add(iis7UrlRewriteServerVariable, headerValue);
}
}
(Note that, in the above method, I'm removing the header from Request.ServerVariables but still retaining it, stashing it in Context.Items. The reason for this is that I need access to the header value later on in the request pipe.)
Hope this helps!
I think you're trying to hard to use GET. Try changing the request method to POST and put those query string parameters into the request body.
Long URL does not help SEO as well, does it?
I was having a similar max URL length issue using ASP.NET Web API 4, which generated a slightly different error:
The fix for me was described above by updating the Web.config with BOTH of the following tags:
<system.web>
<httpRuntime maxUrlLength="10999" maxQueryStringLength="2097151" />
and
<system.webServer>
<security>
<requestFiltering>
<requestLimits maxUrl="10999" maxQueryString="2097151" />
</requestFiltering>
</security>
It appears that the hard-coded max URL length has been fixed in .NET 4.0. In particular, there is now a web.config section with:
<httpRuntime maxRequestPathLength="260" maxQueryStringLength="2048" />
that let you expand the range of allowed URLs.
참고URL : https://stackoverflow.com/questions/1185739/asp-net-mvc-url-routing-maximum-path-url-length
'Program Club' 카테고리의 다른 글
| xml 속성에서 @null의 안드로이드 의미 (0) | 2020.11.18 |
|---|---|
| std :: strings를 반환해야합니까? (0) | 2020.11.17 |
| 동일한 메서드 이름을 가진 여러 인터페이스에서 상속 (0) | 2020.11.17 |
| Scala에서 어떻게 배열을 패턴 화합니까? (0) | 2020.11.17 |
| MySql은 성능을 봅니다. (0) | 2020.11.17 |