maxRequestLength+maxAllowedContentLength+HTTPS not working - asp.net

I have made a service that i host on an azure webapp. This will be used to upload files. IIS has a built in security feature that limits the file upload size.
To work around this i have put the following in my web.config
<system.webServer>
<security>
<requestFiltering>
<requestLimits maxAllowedContentLength="80000000" />
</requestFiltering>
</security>
</system.webServer>
...
<system.web>
<httpRuntime maxRequestLength="80000" targetFramework="4.5.2" executionTimeout="9000" />
</system.web>
This is however not working for me. As soon as i upload a large file (50mb for example) it hits me with a 404. When i upload a smaller file (10mb) it works fine. The service is a soap and is called over https. The call does not time out, the exception occurs within 5 seks of the call being made, my guess is it uploads 30mb and then it thinks it is under attack and aborts.
Am i missing something here?

You can go to folder:
%windir%\system32\inetsrv\
run command:
appcmd set config -section:requestFiltering -requestLimits.maxAllowedContentLength:80000000
or if you only want to set it for your app, run this:
appcmd set config "Default Web Site/" -section:requestFiltering -requestLimits.maxAllowedContentLength:80000000
also you need to update overrideModeDefault to 'Allow' in web.config:
<section name="requestFiltering" overrideModeDefault="Allow" />
Then you can have your web.config updated with appcmd.exe
Hope this article and this article will help you.
About how to use appcmd.exe, you can see https://technet.microsoft.com/en-us/library/cc772200%28v=ws.10%29.aspx
After that deploy your project to azure webapp and try again.

I did that configuration, but i fixed my problem putting on my ControllerBase something like:
protected override void OnResultExecuting(ResultExecutingContext filterContext)
{
base.OnResultExecuting(filterContext);
if(filterContext.Result.GetType().Name == "JsonResult")
filterContext.Result.GetType().GetProperty("MaxJsonLength").SetValue(filterContext.Result, int.MaxValue);
}

For classic ASP users also check this settings in addition to the web.config settigns:
IIS > CLick on Website > ASP > Limit Properties > Maximum request entity body limit

In my case, the problem was because the configuration of httpProtocol in the web.config file had the 'allowKeepAlive' in false.
<httpProtocol allowKeepAlive="false">
I deleted the allowKeepAlive="false" (making it uses the default value of true) and all worked with big files (configuring the 'maxrequestlength' and 'maxallowedcontentlength')

Related

Api is giving 404 when added + as part of URL (%2B)

I am using asp.net core 3.1 and receiving values from URL. Its working fine but when I add "+" sign as a part of URL, it gives 404.
Example : localhost:9000/api/get/%2B12/values
+ is a special character. It should ideally be should be URL encoded as %2B.
Turns out it's not really required though (like in the screenshot below) but I still recommend it. (See: URL encoding the space character: + or %20?)
Here's a working example controller:
[ApiController]
public class ExpController : Controller
{
[Route("/api/exp/{arg}/values")]
public IActionResult Test(int arg) =>
Ok($"The arg is: {arg}");
}
Note how the route parameter is a int. For more complex values (other than just 12, +12, -12; eg: 12+12) the route will need to be a string instead.
version above IIS7 will refuse to request the URL contains symbols such as '+' by default. The following modifications are required. You need add the following nodes in web.config:
<system.webServer>
<security>
<requestFiltering allowDoubleEscaping="true"/>
</security>
</system.webServer>
But now the .net core project does not have web.config to configure IIS options. You need to go to the location:
vs project location /.vs/config/applicationhost.config to add the above node.
Note that the .vs folder is a hidden folder and needs to be set visible.
Option 1 :
Mess with config to bypass request validation / allowDoubleEscaping (Asp.Net)
You need to be aware for certain risk/vulnabilirities described here:
https://stackoverflow.com/a/53621095/4798459
.netcore :
Since this issues is related to IIS, not your solution. You need to handle a web.config
Create a new web.config on the root of your project.
Right click, properties, set "Copy to Output Directory" to "Copy Always"
When you publish a .net core app, a "basic web.config" file is created. (For iis)
You need to copy the content of the "basic web.config".
You can find the auto-generated web.config file:
Where your app is already published (local server?)
You can also publish your api temporarly to a random path on your PC, see details here https://docs.devexpress.com/OfficeFileAPI/401445/dotnet-core-support/publish-net-core-application)
The web.config should like so, i added the tag with a a commentt
<configuration>
<location path="." inheritInChildApplications="false">
<system.webServer>
<!-- XML node <security> is added to allow allowDoubleEscaping and add support for + paremeter in a route. Risk:https://stackoverflow.com/a/53621095/4798459 -->
<security>
<requestFiltering allowDoubleEscaping="true"></requestFiltering>
</security>
<handlers>
<add name="aspNetCore" path="*" verb="*" modules="AspNetCoreModuleV2" resourceType="Unspecified" />
</handlers>
<aspNetCore processPath="dotnet" arguments="[.\SolutionName.Namespace.dll]" stdoutLogEnabled="false" stdoutLogFile=".\logs\stdout" hostingModel="inprocess" />
</system.webServer>
</location>
</configuration>
Make sure that the step 2 is done before publishing your app otherwise it wont work.
Not tested with iisexpress
Option 2
Change pramater type in the api. Intead of being on the route, use a queryString instead
Option 3
Custom solution for request filtetring /routing, which i don't have any example, and seems a bit "over the top".
Option 4, to avoid:
Use an other solution for encoding / decoding special caracter (I have not tried)
https://stackoverflow.com/a/55637235/4798459

IIS error 500.19 error when reading web.config

I am running IIS under Windows Server 2016 and I'm trying to run an ASP.Net core 3.1 application but I can't get past this error:
500.19 error
(The language in the picture is Hungarian, but it contains no useful information whatsoever, just an example)
Here is my web.config
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<location path="." inheritInChildApplications="false">
<system.webServer>
<handlers>
<add name="aspNetCore" path="*" verb="*" modules="AspNetCoreModuleV2" resourceType="Unspecified" />
</handlers>
<aspNetCore processPath=".\Minibizz.Routing.Web.exe" stdoutLogEnabled="false" stdoutLogFile=".\logs\stdout" hostingModel="inprocess" />
</system.webServer>
</location>
</configuration>
What am I missing?
P.S.: The web.config was created by Visual Studio 2019.
The reason behind the issue:
That error message goes on to say what exactly is bad about your configuration file, hence you should refer the “Config Error” and “Config Source” sections. This problem occurs because of the ApplicationHost.config file or the Web.config file contains a malformed or unsupported XML element.
if you are using url rewrite rule then install url rewrite Extention of iis. Enable ANCM logging, ie. set stdoutLogEnabled="true" stdoutLogFile=".\logs\stdout\" (I think the path needs to end by a backslash), then run the web app and see if something gets logged into the stdout folder. Verify that the log directory exists at the path referenced by the web config. If it does not, create it. The path shown in your config would place the "logs" directory in the root folder of the deployed site. Verify that the application pool has to write access to the logs directory.
Make sure you installed the .net bundle.check that you installed below iis feature:
You may also need to verify that the path to the dotnet executable exists in the deployment machine's environment variables. To check this, first find the path where dotnet.exe is installed. It is generally located in either C:\Program Files\dotnet or C:\Program Files (x86)\dotnet. Once you know the path, ensure that the path exists in your Environment Variables.
The web.config content seems to be correct. If you use a clean web.config copy, does the problem persist? If the issue can be solved by replacing web.config with clean configuration content, then the problem is exactly with this web.config. In this case, I suggest you remove parts of the web.config content to narrow down the issue. If the pages show correctly after you remove one section, then the problem is with that section. You need double-check what's wrong with the section and update the correct configuration.
If the problem remains even with clean web.config content, I suggest you access other pages in different folders in your site to see if the problem still exists.
you could refer this below link for how to publish asp.net core site in iis:
https://learn.microsoft.com/en-us/aspnet/core/tutorials/publish-to-iis?view=aspnetcore-3.1&tabs=visual-studio

Optimized bundles returning 404 when requesting from the website

I'm having this weird problem when I set:
BundleTable.EnableOptimizations = true;
When I try to open my website it just won't load, when I open Chrome's console I see the following message:
GET /localhost/bundles/scripts/angularjs/commonmodules?v=13-uWpwzN3U6kiHVssXRdpywHxrn09twvYKwoDVN3SU1 404 (Not Found)
However, if I try to open the link shown on chrome's console, it loads just fine, in other words, the link is found when I try to open it directly, but the server (IIS 7.5) returns a 404 when a page tries to link it through a tag.
Have anyone been through such a weird behavior?
The virtual paths for my bundles do not map for any existing file or directory, I include them using the following code:
var myBundle= new ScriptBundle("~/bundles/scripts/angularjs/bootstrapping");
bootstrapping.Include("~/app/app.js")
.Include("~/app/config.js")
.Include("~/app/config.exceptionHandler.js")
.Include("~/app/config.route.js");
bundles.Add(bootstrapping);
And I already tried to add the following lines on web.config's system.webServer:
<modules runAllManagedModulesForAllRequests="true">
<remove name="BundleModule" />
<add name="BundleModule" type="System.Web.Optimization.BundleModule" />
</modules>
I'm not sure if this may be related, but I'm using Umbraco v7 on this website, and this only happens if I set EnableOptimizations to "true".
If I remember correctly it's umbraco config related.
Locate the key umbracoReservedPaths (in appSettings) in your web.config and add the path to bundles there, like so:
<add key="umbracoReservedPaths" value="~/umbraco,~/install/,~/bundles/"/>

web.config in subdirectory in mvc 4

This question seems to have been asked quite a bit but none actually solve the problem for me. I have an ASP.NET MVC4 application with an area. Inside this area I have a web.config with overridden appsettings. These settings don't seem to be picked up when attempting to read them in a controller within the area.
-MyApp
-Areas
-MyArea
-Controllers
-MyController
-Web.config
-Web.config
In MyApp\Web.config I have:
<appSettings>
<add key="DefaultDisplayMode" value="Configuration" />
</appSettings>
In MyApp\Areas\MyArea\Web.config I have:
<appSettings>
<add key="DefaultDisplayMode" value="Review" />
<add key="SubSetting" value="Testing" />
</appSettings>
In MyController if I query the app settings, I see:
DefaultDisplayMode: Configuration
I expect to see:
DefaultDisplayMode: Review
SubSetting: Testing
I've tried with both:
System.Configuration.ConfigurationManager.AppSettings["..."]
System.Web.Configuration.WebConfigurationManager.AppSettings["..."]
I even tried with the following (over the top) structure with no luck:
-MyApp
-Areas
-MyArea
-Controllers
-MyController
-Web.config
-Web.config
-Web.config
Does anybody know why my subdirectory appSettings aren't working?
IIS will load the web.config based on the URL, not based on the code that your routed request executes.
You can create an empty folder structure that mimics the required route and add the config file there. If that does not work, you can use <location> tag in the main configuration file - but the path in the location tag also has to match the URL and not the code.

ASP.NET - Deployment Issues - Enabling Stack Trace / Trace Listener Log via the Web.Config to find the cause of Internal Server 500 Error

I am getting a Internal Server 500 error after deploying an application that has compiled without errors on my local machine. The server that the application is deployed on has a ton of security so I need to specify read and write access for every directory. This application uses windows authentication and a web service to populate drop down boxes via a proxy. I think there might be an issue connecting to the web service or an issue with the read/write security on the files, or an issue with the active directory authentication.
I edited the web.config so that it would display more information as to the cause of the error with the following code:
<system.web>
<customErrors mode ="Off"></customErrors>
<compilation debug="true" strict="false" explicit="true" targetFramework="4.0" />
<trace enabled="true" pageOutput="true" />
<authentication mode="Windows"/>
<authorization>
<allow roles="alg\ADMIN_USER" />
<deny users="*" />
</authorization>
<client>
<endpoint address="http://63.236.108.91/aCompService.svc" binding="basicHttpBinding"
bindingConfiguration="BasicHttpBinding_IAcompService" contract="aComp_ServiceReference.IAcompService"
name="BasicHttpBinding_IAcompService" />
</client>
I am now getting the following Error:
500 - Internal server error.
There is a problem with the resource you are looking for, and it cannot be
displayed.
I would like to see the stack trace with the source of the error.
What am I supposed to put in the web.config file so it displays the full stack trace?
What needs to be changed on the website from locally run to deployment?
Update- The deployment guy lifted some security read/write restrictions and now I get
Parser Error Message: The connection name 'ApplicationServices' was not found in
the applications configuration or the connection string is empty.
To get rid of the error, I removed the AspNetSqlRoleProvider declared on Line 72 and still
got an error. I then removed the AspNetWindowsTokenRoleProvider and all the provider info
and got the following Error:
Exception message: Default Role Provider could not be found.
Our hosting is done all remotely but the server guy can login to the local webserver remotely. It looks like the server guy didn't post the files in the right place. Now, I now get the error:
There is a problem with the resource you are looking for, and it cannot
be displayed.
Any ideas on how to fix these issues?
Thanks for looking!
Do you have a web.config at another location in the application's folder hierarchy that could be overriding the change you're making? I've seen confusion before when devs have copied a web.config up a level to retain a copy of it while making test changes.
That can be a source of much head-scratching.
Perhaps using impersonation should help?
I added the following in web.config:
<authentication mode="Windows"/>
<identity impersonate="true"/>
I added WriteToEventLog code so that I can track errors in the event log by the method.
Catch Ex As Exception
WriteToEventLog(Ex.Message, "GetCarriers-Method", EventLogEntryType.Error, "aComp-utility")
Catch ex As Exception
WriteToEventLog(ex.Message, "GetMarketingCompanies-Method", EventLogEntryType.Error, "aComp-utility")
Perhaps adding a TraceListenerLog should help?
Reference MSDN for more info on this code. I added the following in web.config:
<configuration>
<system.diagnostics>
<trace autoflush="false" indentsize="4">
<listeners>
<add name="myListener"
type="System.Diagnostics.EventLogTraceListener"
initializeData="TraceListenerLog" />
</listeners>
</trace>
</system.diagnostics>
</configuration>
should i also add the following on default.aspx.vb ?
Overloads Public Shared Sub Main(args() As String)
' Create a trace listener for the event log.
Dim myTraceListener As New EventLogTraceListener("myEventLogSource")
' Add the event log trace listener to the collection.
Trace.Listeners.Add(myTraceListener)
' Write output to the event log.
Trace.WriteLine(myTraceListener)
End Sub 'Main
I was able to over come this same problem by making a copy of my config file and then removing one segment and then testing the results one step at a time. What I discovered is that after I removed my handelers it worked fine.

Resources