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

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

Related

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

LessAssetHandler is not invoked for path inside area

I have a problem with LessAssetHandler which ships with BundleTransformer.Less library. I use LessAssetHandler in debug mode as a HttpHandler for transforming less files. Everything works fine except that the files inside ASP.NET areas are not handled by LessAssetHandler. For example file /Content/Style/page.less is handled by LessAssetHandler, byt for file /Areas/Admin/Content/Style/page.less this handler is not invoked. I have configured handler in the folling way:
<system.webServer>
<handlers>
<add name="LessAssetHandler" path="*.less" verb="GET" type="BundleTransformer.Less.HttpHandlers.LessAssetHandler, BundleTransformer.Less" resourceType="File" preCondition="" />
<handlers>
</system.webServer>
How can I force MVC to route less files from area through LessAssetHandler?
Registration of LessAssetHandler is correct. The exact same code is added to Web.config file during installation of NuGet package.
BundleTransformer.Less can work in ASP.NET MVC application with areas. It is possible, that you have incorrectly registered the bundle.
Bundle registration should look like the following:
var adminStylesBundle = new CustomStyleBundle("~/Bundles/AdminStyles");
adminStylesBundle.Include("~/Areas/Admin/Content/Style/page.less");
adminStylesBundle.Orderer = nullOrderer;
bundles.Add(adminStylesBundle);

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.

How to map the root URL in an ASP.NET application?

I have the following in my Web.config:
<httpHandlers>
. . .
<add verb="GET,HEAD" path="/" type="Vis.Web.BootHandler, Vis" />
</httpHandlers>
That HTTP handler returns a static HTML page, just to see if it works.
Now when I run my web application (which has no Default.aspx or the likes) I get the default directory listing instead. When I change the path to "/foo" it works perfectly fine.
I tried "" for the path, it yields the directory listing as well. Same having it as "/foo" and then adding a URL mapping to for "", "~", "~/" and "/"
How do I handle the web root / override the directory listing with a HTTP handler?
UPDATED: Regarding comment
This can't be done in the development server as it requires a feature of IIS.
ORIGINAL:
You need to add a wildcard application mapping to the asp.net DLL so that all requestes (even for directories) are run through the .net runtime and therefore your HTTP Handler.
Check out http://www.microsoft.com/technet/prodtechnol/windowsserver2003/library/IIS/5c5ae5e0-f4f9-44b0-a743-f4c3a5ff68ec.mspx
for more info
In addition to what #Greg B said you will need to add a dummy default.aspx page and register your handler using /* path:
<httpHandlers>
. . .
<add verb="GET,HEAD" path="/*" type="Vis.Web.BootHandler, Vis" />
</httpHandlers>

Resources