How to configure the web.config to allow requests of any length - c#

I am building a site in which i would like to create a file client side from the value of a textarea element.
I have the code in place to do this, but i am getting this error
HTTP Error 404.15 - Not Found The request filtering module is
configured to deny a request where the query string is too long.
Is there a way to override this so that I am able to process requests of any size?
If not, is there a way to generate files client side without using the filesystem/active x object?
thanks

Add the following to your web.config:
<system.webServer>
<security>
<requestFiltering>
<requestLimits maxQueryString="32768"/>
</requestFiltering>
</security>
</system.webServer>
See:
http://www.iis.net/ConfigReference/system.webServer/security/requestFiltering/requestLimits
Updated to reflect comments.
requestLimits Element for requestFiltering [IIS Settings Schema]
You may have to add the following in your web.config as well
<system.web>
<httpRuntime maxQueryStringLength="32768" maxUrlLength="65536"/>
</system.web>
See: httpRuntime Element (ASP.NET Settings Schema)
Of course the numbers (32768 and 65536) in the config settings above are just examples. You don't have to use those exact values.

In my case ( Visual Studio 2012 / IIS Express / ASP.NET MVC 4 app / .Net Framework 4.5 ) what really worked after 30 minutes of trial and error was setting the maxQueryStringLength property in the <httpRuntime> tag:
<httpRuntime targetFramework="4.5" maxQueryStringLength="10240" enable="true" />
maxQueryStringLength defaults to 2048.
More about it here:
Expanding the Range of Allowable URLs
I tried setting it in <system.webServer> as #MattVarblow suggests, but it didn't work... and this is because I'm using IIS Express (based on IIS 8) on my dev machine with Windows 8.
When I deployed my app to the production environment (Windows Server 2008 R2 with IIS 7), IE 10 started returning 404 errors in AJAX requests with long query strings. Then I thought that the problem was related to the query string and tried #MattVarblow's answer. It just worked on IIS 7. :)

If you run into this issue when running an IIS 8.5 web server you can use the following method.
First, find the "Request Filtering" module in the IIS site you are working on, then double click it...
Next, you need to right click in the white area shown below then click the context menu option called "Edit Feature Settings".
Then the last thing to do is change the "Maximum query string (Bytes)" value from 2048 to something more appropriate such as 5000 for your needs.

Something else to check: if your site is using MVC, this can happen if you added [Authorize] to your login controller class. It can't access the login method because it's not authorized so it redirects to the login method --> boom.

It will also generate error when you pass large string in ajax call parameter.
so for that alway use type post in ajax will resolve your issue 100% and no need to set the length in web.config.
// var UserId= array of 1000 userids
$.ajax({
global: false,
url: SitePath + "/User/getAussizzMembersData",
"data": { UserIds: UserId},
"type": "POST",
"dataType": "JSON"
}}

I had a similar issue trying to deploy an ASP Web Application to IIS 8. To fix it I did as Matt and Leniel suggested above. But also had to configure the Authentication setting of my site to enable Anonymous Authentication. And that Worked for me.

I had to add [AllowAnonymous] to the ActionResult functions in my login page because the user was not authenticated yet.

If your website is using authentication, but you don't have the correct authentication method set up in IIS (e.g. Basic, Forms etc..) then the browser will be getting stuck in a redirect loop. This causes the redirect url to get longer and longer until it explodes.

For someone who experiences this while running the apps from Visual Studio, while using IIS Express, first you have to locate the applicationhost.config file being used by the application. See the answer at https://stackoverflow.com/a/41553876/1849880 on how to locate the applicationhost.config file. Then, you can change the maxQueryString value as explained above.

HTTP Error 404.15 - Not Found The request filtering module is
configured to deny a request where the query string is too long.
To resolve this problem, check in the source code whether the Form tag has a property method is get/set state.
If so, the method property should be removed.

Related

C# web Api Long url Not working

I have the following web API url which is not working
www.localproject.com:843/api/user/validate/eyJhbGciOiJodHRwOi8vd3d3LnczLm9yZy8yMDAxLzA0L3htbGRzaWctbW9yZSNobWFjLXNoYTI1NiIsInR5cCI6IkpXVCJ9eyJ0ZW1wVXJsIjoie1wiQ3VzdG9tZXJJZFwiOjEsXCJDb3Vyc2VJZFwiOjEsXCJUb2tlblwiOm51bGwsXCJFeHBpcnlcIjpcIjIwMTgtMDQtMThUMTc6MzU6MTMuOTQ2MjM2NCswNTowMFwifSJ9uvm7jZ3us5UFa1hqh4bod2cSamcxF2rRUbfxs7DHQs
whenever I hit the above url It gives me following error
Bad Request - Invalid URL
HTTP Error 400. The request URL is invalid.
I updated my web.config to this as well but still not working.
<httpRuntime targetFramework="4.6.1" maxRequestLength="20480" maxUrlLength="6144" relaxedUrlToFileSystemMapping="true" />
I also tried editing registry but no luck.
How to allow long url using web api?
By default, HTTP.sys permits 255 segments at a maximum length of 260 characters each. That 260 character limit is why you are seeing this issue.
To fix this you need to make a registry change.
Navigate to:
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\HTTP\Parameters
Add a DWORD value named UrlSegmentMaxLength and set its value to something like 500 or say 1000.
While you can probably avoid reboot by restarting the HTTP System Service thru command line is a possibility "net stop http" and "net start http", but because several other services depend upon this service like WWW, Print Spooler, SSDP Discovery etc. I will still recommend rebooting the server.

c# URL with plus sign not running through custom HttpModule

I've got a custom HttpModule to redirect legacy URLs from an old build of the site which checks the incoming request URL against a database table of redirects.
However, when the incoming request URL contains a plus (+) sign, the request doesn't fall through the HttpModule - it works as expected for standard URLs.
For example, these URLs works:
http://www.example.com/sample-url
http://www.example.com/sample url
http://www.example.com/sample%20url
These don't:
http://www.example.com/sample+url
http://www.example.com/sample%2Burl
Here's my module declaration:
<add name="LegacyUrlHttpModule" type="Web.LegacyUrlHttpModule, Framework.Web" preCondition="managedHandler" />
Am I missing a setting here or something?
Scott Hanselmann wrote a nice blog post explaining how you could enable all kind of crap symbols in the Path portion of an url.
His conclusion is the following:
After ALL this effort to get crazy stuff in the Request Path, it's
worth mentioning that simply keeping the values as a part of the Query
String (remember WAY back at the beginning of this post?) is easier,
cleaner, more flexible, and more secure.
So basically if you have such characters in a url, those characters should be passed as query string parameters instead of attempting to pass them in the Path portion.
IIS rejects + in URLs by default. A workaround would be to allowDoubleEscaping
<system.webServer>
<security>
<requestFiltering allowDoubleEscaping="true" />
</security>
</system.webServer>
but beware that this may make your site more vulnerable to malicious URLs.
You can follow the below steps:
in the IIS webserver section, double click the 'Request Filtering' icon
in the 'File Name Extension' right click->Edit Feature Settings...' the file 'web.config'
check the option 'Allow double escaping' (this option is unchecked by default)
repeat all above 3 steps for the 'default website' (or whatever you have given the name to your site)
re-start the IIS

401 Unauthorized error web api mvc windows authentication

I am getting 401 unauthorized error . My web service is written in mvc . in IIS configured to use windows authentication.
Below is screen shot of fiddler
When I hit URL from browser it gives me popup window to enter user name and password.
How can I avoid popup window?
I am calling this web api from another window service.
I suspect that the two web services may be hosted on the same server. In this case, the problem may be caused by the loopback check. In order to test, try referencing the service without using the fully qualified domain name and see if it works. If it does, use the following steps to specify which host names are on the local computer.
Method 1: Specify host names (Preferred method if NTLM authentication is desired) (https://support.microsoft.com/en-us/help/926642/)
To specify the host names that are mapped to the loopback address and can connect to Web sites on your computer, follow these steps:
Set the DisableStrictNameChecking registry entry to 1. For more information about how to do this, click the following article number to view the article in the Microsoft Knowledge Base: 281308 Connecting to SMB share on a Windows 2000-based computer or a Windows Server 2003-based computer may not work with an alias name
Click Start, click Run, type regedit, and then click OK.
In Registry Editor, locate and then click the following registry key:
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Lsa\MSV1_0
Right-click MSV1_0, point to New, and then click Multi-String Value.
Type BackConnectionHostNames, and then press ENTER.
Right-click BackConnectionHostNames, and then click Modify.
In the Value data box, type the host name or the host names for the sites that are on the local computer, and then click OK.
Quit Registry Editor, and then restart the IISAdmin service.
https://learn.microsoft.com/en-gb/archive/blogs/sharepoint_foxhole/disableloopbackcheck-lets-do-it-the-right-way
**Edited to be in the form of an answer and include detailed steps from referenced links
If you are using WebClient you need to set the Credientials. How are you calling the web api from the windows service?
My 2 cents: I faced a scenario where we were baffled by an HTTP 401 when requesting an image when the web application was deployed. We use WiX as our packaging and install solution.
In this specific case, the image wasn't being packaged by the installer and hence the path did nor exist on the deployed instance.
One may wonder why this threw a 401 when a 404 (not found) would have been expected - my understanding is that since our path was not directly under the root but something like root/content/images/image.png, and I made an anonymous request, I got a 401 (unauthorized) as I did not have the access to browse the directory. I confirmed this by adding an Authorization header to my request and then as expected I got a 404.
You can specify the username and password as part of the URL:
http://username:password#www.example.com/foo/bar/baz
Note: Just because you can doesn't mean you should. While this can be a temporary solution to test things, I would not suggest doing this in production. And in the old days, this is how we did it. But as #DiskJunky points out, "URLs are easily visible to pretty much anything/anyone" which includes your browser history, server logs, and perhaps worse.
I added below lines in web config to fix the issue and it worked.
<security>
<authorization>
<add accessType="Allow" users="*" />
</authorization>
</security>

ASP.Net MVC returns 404 for URLs with Action parameters but not for default route

I am using a WebForms application with some MVC components added in. The idea is to move more and more of the app over to MVC but there is no way it can be transitioned all at once. For various reasons I cannot control it must use ASP.Net 2.0 and MVC 2.0 since those are what ship built-in. I must also support IIS 6 and IIS 7.
First, I am well aware of the problems with extensionless routing and I am not attempting to use it so there are no issues with wildcard mappings, etc. I first attempted to use my routes ala "{controller}.aspx/{action}/{id}" but after banging my head on the wall I switched to "{controller}.mvc/{action}/{id}" but am having the same issues.
Second, I cannot get this to work even in IIS 7 Integrated mode on my dev machine, let alone Classic mode or IIS 6. It all runs correctly under Cassini but once I deploy to IIS 7 the MVC components break. Since this is on my dev machine I know ASP.Net is registered with IIS correctly and I can see all the inherited HTTP handlers in the control panel (eg: ASPX maps to PageHandlerFactory).
Symptoms:
All ASPX WebForms requests work perfectly.
An MVC requests to just the controller with no action/id specified get routed to MVC and execute properly as well.
Any request to an MVC route with an action or id immediately returns a 404. It is as if IIS thinks the ".mvc" extension is part of the folder path so it ignores the HTTP handler and returns a 404.
In other words:
/app/WebForm.aspx - HTTP 200 OK, executes WebForm.aspx.cs code-behind
/app/Fancy.mvc - HTTP 200 OK, executes /Controllers/FancyController.cs, Index method
/app/Fancy.mvc/DoThingy - HTTP 404 NOT FOUND, even though FancyController has DoThingy method
Bad Solutions: I have tried things like setting runAllManagedModulesForAllRequests but not only is that bad for performance it also breaks my Web Forms as well. Even when I set it to ignore all routes with .ASPX in them they still break.
I cannot use wildcard mapping so that is no help.
Other Details:
I setup my HTTP Handler in web.config/system.WebServer. It is the first handler listed.
<add name="MvcRoutingHandler" preCondition="integratedMode" verb="*" path="*.mvc" type="System.Web.Routing.UrlRoutingHandler, System.Web.Routing, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" resourceType="Unspecified" />
It doesn't seem to matter what handler I specify or what options - IIS just doesn't seem to be examining any of this configuration (again because it seems to think the Fancy.mvc part of the path is a directory name, doesn't find that directory, then bails).
My routes:
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.IgnoreRoute("{resource}.aspx/{*pathInfo}");
routes.IgnoreRoute("{resource}.asmx/{*pathInfo}");
routes.IgnoreRoute("{resource}.aspq/{*pathInfo}");
routes.IgnoreRoute("{resource}.svc/{*pathInfo}");
routes.MapRoute("Default",
"{controller}.mvc/{action}/{id}",
new { action = "Index", id = UrlParameter.Optional }
);
Update: I tried using IIS 7 Classic mode; I then added a .mvc mapping in the IIS Manager pointing at the asp_net ISAPI dll and got the same result
OK just so others don't look foolish, it turns out that this was a problem with URLs... the URL was being sent to the root of the site, not the app directory. I should have checked that to begin with. I didn't think this was the problem because when I manually typed the URL into the address bar it worked on the Index but the action method required HttpPost, so it was a combination of factors that made the script and manually-entered addresses spit out the same error message.
For anyone else mixing WebForms and MVC, double and triple-check that your URLs are correct. Here is some code I am now using on the WebForms master page so my client-side JS can know where to route MVC requests:
string baseUrl = Request.Url.GetLeftPart(UriPartial.Authority);
if (baseUrl.EndsWith("/")) baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
baseUrl = baseUrl + ResolveUrl("~/");
Page.ClientScript.RegisterHiddenField("BaseUrl", baseUrl);

mvc routing generates iis 7.5 error forbidden

I my WebApplication I have an ASPX WebForms Page here:
~/ASPWebforms/MyFolder/Default.aspx
If I use this code:
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapPageRoute(
"SomeRoute",
"Test/{reportname}",
"~/ASPWebforms/MyFolder/{reportname}.aspx"
);
and then enter this in the browser:
localhost/MySite/Test/Default
I get the desired the result: The page ~/ASPWebforms/MyFolder/Default.aspx is displayed.
But if I use the following
code
routes.MapPageRoute(
"SomeRoute",
"Test/",
"~/ASPWebforms/MyFolder/Default.aspx"
);
and try
localhost/MySite/Test
IIS 7.5 says:
HTTP Error 403.14 - Forbidden The Web server is configured to not list
the contents of this directory.
Do I do something wrong in the last piece of code?
Thx in advance!
I had something a lot like this, and from reading around it seems like it could be caused by several different things. In my case I had a route like this:
routes.MapPageRoute("signin", "signin", "~/SignIn/SignIn.aspx")
So the route path is /signin, but there is also a folder called /signin containing the .aspx page.
I got the error response
HTTP Error 403.14 - Forbidden. The Web server is configured to not list the contents of this directory.
This was fixed when I added this line to the route config:
routes.RouteExistingFiles = true;
The error message has a grain of truth in it: /signin is a directory, and the web server is configured to not list files in it. It seems that this file path takes precedence over the route unless you configure it otherwise.
Other things that I tried:
I did not need to use a different overload of MapPageRoute
I did not need to add UrlRoutingModule to the web.config under
system.webServer|Modules. It works without that.
It works without the web.config setting
<modules runAllManagedModulesForAllRequests="true">
I do have that for other reasons, but if I remove it then this fix still works.
I did install the server feature "Http Redirection" in the machine's Server Manager|Web
Server|Add Role Services dialogue but after removing it again this still works.
Reinstall .NET 4 x86 & x64 on IIS 7.5 and setup your web site .net version.
I write simple commands by default x86.
Stopping IIS:
1)iisreset /stop
Stup command(for iis by default .net stup):
2) cd %windir%\Microsoft.NET\Framework\v4.0.30319
3)aspnet_regiis.exe -i
Reset command(for iis by defalt .net change to .net 4 version):
4)aspnet_regiis.exe -iru
Starting IIS:
5)iisreset /start
Try setting up the route using one of the overloads that sets default values like so:
routes.MapPageRoute(
"SomeRoute",
"Test/{reportname}",
"~/ASPWebforms/MyFolder/{reportname}.aspx",
false,
new RouteValueDictionary(new {reportname = "Default"})
);
Not massively confident it will sort your problem but with it working with your original example it could well do.

Categories

Resources