Routing requests that end in ".cshtml" to a controller - asp.net-mvc-3

(This is cross-posted to the ASP.NET forms)
I'm working on the WebGit .NET project, and we are close to a "1.0" release. However, I'm having trouble getting my "Browse" controller (which pulls files out of the repository) to serve-up ".cshtml" files.
I originally had trouble with ".config" and ".cs" files as well, but I fixed that with this in the web.config:
<location path="browse">
<system.webServer>
<security>
<requestFiltering>
<fileExtensions allowUnlisted="true">
<clear />
</fileExtensions>
<hiddenSegments>
<clear />
</hiddenSegments>
</requestFiltering>
</security>
</system.webServer>
</location>
The routing that should be handling this request (that is successfully routing everything else) is:
routes.MapRoute(
"View Blob",
"browse/{repo}/blob/{object}/{*path}",
new { controller = "Browse", action = "ViewBlob", path = UrlParameter.Optional });
Now, whenever I try to access a URL that ends in ".cshtml", it gives a 404, even though my request should have been handled by the "Browse" controller. The files I'm serving-up do not exist on disk, but are instead pulled from a git repository as blobs. Every other file extension that I have tried works just fine.
How can I fix this behavior?
EDIT: I have tried disabling WebPages like so:
<appSettings>
<add key="webpages:Enabled" value="false" />
</appSettings>
But that appears to have no effect.

As a quick workaround, you can put a temporary browse.cshtml file at your application root and put this inside your web.config,
add key="webpages:Enabled" value="false"

This is a known bug in ASP.NET WebPages, which gets implicitly loaded when you are using MVC 3. I don't think there is a straightforward way of disabling this behavior. The only workaround is to use a different extension (specifically, one that is not listed via WebPageHttpHandler.GetRegisteredExtensions())
This will be fixed in MVC 4, however. Sorry for the inconvenience.

Related

.Net Core 2.1 Error 413 on multipart/form-data POST only on IIS not IIS Express

I'm hitting a problem with multipart/form-data POST uploads on IIS. My client is an Angular SPA and my backend is on .Net Core 2.1 (I know it's old).
The backend project is published as Self-Contained win-x64. I'm not sure how it's configured exactly on IIS / Kestrel but the IIS App runs under a specific Application Pool (No managed Code / Integrated). My web.config looks like this:
<configuration>
<location path="." inheritInChildApplications="false">
<system.web>
<httpRuntime maxRequestLength="1048576" />
</system.web>
<system.webServer>
<security>
<requestFiltering>
<requestLimits maxAllowedContentLength="1073741824" />
</requestFiltering>
</security>
<handlers>
<add name="aspNetCore" path="*" verb="*" modules="AspNetCoreModule" resourceType="Unspecified" />
</handlers>
<aspNetCore processPath=".\my.app.exe" stdoutLogEnabled="false" stdoutLogFile=".\log\path" />
</system.webServer>
</location>
</configuration>
In my development environment instead I'm using IIS Expres.
Now I added a multipart/form-data upload, sending form data together with a blob/image. This worked out of the box in development settings. However when I publish to staging environment with real IIS and the above web.config, I always get 413 Request entity too large.
My controller looks like this:
[HttpPost]
[DisableRequestSizeLimit]
[RequestFormLimits(MultipartBodyLengthLimit = int.MaxValue, ValueLengthLimit = int.MaxValue)]
[RequestSizeLimit(int.MaxValue)]
[Route("my/route")]
public ActionResult MyHandler()
I also added limits for Kestrel in Program.cs:
.UseKestrel(options =>
{
options.Limits.MaxRequestBodySize = 104857600; // 100MB
}
)
And to make the weirdness complete the 413 in staging environment only happens in Firefox. I have no idea what else I can do. I also cleared cache in firefox.
After longer search I finally found the necessary setting in IIS to make this work in Firefox. And it has indeed be mentioned in a few sources as the 'last option'. For me it was necessary in this case.
In 'IIS Manager' I selected the backend application and opened 'Configuration Editor'
system.webServer/serverRuntime -> uploadReadAheadSize=2147483647
That maked it work.

How to allow a DELETE method with IIS Express and Web API?

I am trying to send a delete request to my Web API service via Fiddler and am getting back a 405 "Method not allowed" error.
I have read extensively about removing the "WebDAV" module in web.config and similar suggestions (WebDAV is not enabled in my applicationhost.config anyway), but nothing I have tried has worked.
My service is currently running on IIS Express 10 (launching from Visual Studio). I do have this in my web.config file:
<add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="*" type="System.Web.Handlers.TransferRequestHandler"
preCondition="integratedMode,runtimeVersionv4.0"/>
I would have thought the verb="*" piece would have allowed DELETE, but it does not seem to work.
One other note - when I inspect the response in Fiddler, under the Security heading it says: Allow: GET, POST.
I am not sure where that "Allow" parameter is being set (I am new to Web API).
Any help would be greatly appreciated. Please let me know what other information you need from me and I will add it.
Thank you!
Just reproduced this by creating a new webapi project [targeting .net framework 4.7.1]
Through Fiddler, I can hit the DELETE endpoint without any changes to web.config.
Please make sure to use correct endpoint including the id parameter.
e.g http:localhost:xxxx/api/values/id // please include the id and xxxx is port number.
If http:localhost:xxxx/api/values is used without id , I get the same result 405 Method Not Allowed
Hope this helps.
You can modify the IIS Express applicationHost.config in the %userprofile%\documents\IISExpress\config folder.  To enable PUT and DELETE for extensionless Urls scroll down to the bottom of the IIS Express applicationHost.config file and look for a handler entry that starts with: <add name="ExtensionlessUrl-Integrated-4.0".... In the "verb" attribute add PUT and DELETE so the "verb" attribute looks like:  verb="GET,HEAD,POST,DEBUG,PUT,DELETE"
Update your web config like this
<system.webServer>
<validation validateIntegratedModeConfiguration="false"/>
<modules runAllManagedModulesForAllRequests="true">
<remove name="WebDAVModule"/> <!-- ADD THIS -->
</modules>

Getting error Session state can only be used when enableSessionState is set to true

I upgraded Kentico site into version Kentico version 11. I am getting error of
Session state can only be used when enableSessionState is set to true, either in a configuration file or in the Page directive. Please also make sure that System.Web.SessionStateModule or a custom session state module is included in the \ section in the application configuration.
I performed solution for that:
I applied in web.config
sessionState cookieless="UseCookies" mode="InProc"
sqlConnectionString="data source=127.0.0.1;Trusted_Connection=yes"
stateConnectionString="tcpip=127.0.0.1:42424" timeout="20"
but not working.
I also added in page tag in web.config
pages enableSessionState="true" validateRequest="false" clientIDMode="AutoID"
controlRenderingCompatibilityVersion="4.0"
but not working.
I also start ASP.Net services but not working.
My .Net framework is 4.6
Correction on my last post now that i have a normal web.config in front of me.
Default Session State is:
<sessionState mode="InProc" stateConnectionString="tcpip=127.0.0.1:42424" sqlConnectionString="data source=127.0.0.1;Trusted_Connection=yes" cookieless="false" timeout="20" />
Nothing else on the pages part. Try that. Emphasis on the cookieless="false" as that is different than your configuration.
at your web.config add the following
<modules runAllManagedModulesForAllRequests="true">
.
.
.
.
</modules>

being redirected to wrong loginUrl -> account/login instead of account/LOGON

I have a strange error I have never run into before.
I secured a controller with:
[Authorize(Roles = "admin")]
public class LoggingController : Controller
When a non-admin user tries to access any protected content, they are redirected to:
http://localhost:50501/Account/Login?ReturnUrl=%2flogging
note: account/login and NOT account/logon
The AccountController.Login action does not exist.
web.config has:
<authentication mode="Forms">
<forms loginUrl="~/Account/LogOn" timeout="2880" />
</authentication>
I can of course implement the Login action and redirect to Logon.
I am just puzzled and would like to know why this happens.
Search your project for login - it has to be specified somewhere. Is there any other web.config value overriding this (maybe looking at a child root and the parent value is being used)
Also is there any redirect that is happening? Are there any defaults set in your machine's web.config?
Is your default url on the project set to be a /login?
Install glimpse route debugger to see which route is being used for this page as well.
EDIT:
A little more research yields a known issue.
Check out this link:
ASP.NET MVC issue with configuration of forms authentication section
Theres a bug in mvc 3 beta - are you running the beta bits?
Also notice the mentioned item in the above url for RTM bits:
<add key="loginUrl" value="~/LogOn" />
Also check out
http://forums.asp.net/p/1616153/4138366.aspx
EDIT 2
Below is a solid comment about a potential source of this from #santiagoIT (upvote his comment please if the specifics help you)
Today I discovered the root of this problem: I had added 'deployable dependency' on 'ASP.NET Web Pages with Razor Syntax'. This adds a reference to: WebMatrix.Data.dll This assembly has a class with a static constructor that does the following: static FormsAuthenticationSettings(){ FormsAuthenticationSettings.LoginUrlKey = "loginUrl"; FormsAuthenticationSettings.DefaultLoginUrl = "~/Account/Login";} That explains!
This worked for me and I'm using MVC 3
<appSettings>
<add key="loginUrl" value="~/Account/LogOn" />
</appSettings>
<system.web>
<authentication mode="Forms">
<forms loginUrl="~/Account/LogOn" name=".ASPXFORMSAUTH" />
</authentication>
</system.web>
Also I found that adding the followinf part to the web config (only during debugging the config) helped speed up my debugging as had to authenticate for ANY page.
<authorization>
<deny users="?" /> <!-- remove after debugging -->
</authorization>
Just simply remove the WebMatrix dll if they are present in your deployed bin folder.
I fixed it this way
1) Go ot IIS
2) Select your Project
3) Click on "Authentication"
4) Click on "Anonymous Authentication" > Edit > select "Application pool identity" instead of "Specific User".
5) Done.

Disable OutputCaching in MVC3 when running in DEBUG or under Debugger?

I am trying to disable output caching in a MVC3 app when in debug. I am specifying output caching in the controllers (via the attribute) but don't want to have to #if DEBUG all over my code. I expected this to work:
// In Web.config.debug
<system.web>
<caching>
<outputCache enableOutputCache="false"
xdt:Transform="Replace" />
</caching>
But this seems to be ignored. Any other ideas how to do it system wide without nasty global.asax code or #if DEBUGs everwhere?
The web.config.debug file is used only when you build a deployment package. If you run your site locally in Cassini for example it is completely ignored. So you may try disabling cache in your web.config:
<system.web>
<caching>
<outputCache enableOutputCache="false" />
</caching>
</system.web>
and in your web.config.release enable the cache. Note though that if you don't use the web deployment package feature those files are completely ignored.
I would think that would work as well. You may want to also try setting enableFragmentCache to false. Per this link:
the EnableFragmentCache property is
set to false, no page is cached on the
server, regardless of the settings in
# OutputCache directive or caching
profile used by the page. For more
information, see
OutputCacheSettingsSection and
OutputCacheProfile.
If you use IIS version > 7
You should:
<system.webServer>
<caching enabled="true"/> //false in webconfig.debug
</system.webServer>

Resources