ASP.NET- 404 when attempting to open PDF [duplicate] - c#

I want to be able to request static .html files which are located in the ~/Views folder.
According to the documentation, the routing system checks to see if a URL matches a disk file before evaluating the application's routes.
But when I request the file a 404 error arises.
My file is located in ~/Views folder.
The URL is: http://[localhost]/Views/HtmlPage1.html
What have I missed?

I want to be able to request static .html files which are located in the '~/Views' folder.
You can't. There's a web.config file in this folder which explicitly forbids accessing any file from it. If you want to be able to access files from the client those files should not be placed in the Views folder which has a special meaning in ASP.NET MVC.
You could have a ~/Static folder where you could place your HTML files. And then access it like that:
http://example.com/yourapplicationname/static/foo.html

To allow files like js and html in Views folder edit the web.config in views-Folder:
<system.webServer>
<handlers>
<add name="JavaScriptHandler" path="*.js" verb="*"
preCondition="integratedMode" type="System.Web.StaticFileHandler" />
<add name="HtmlScriptHandler" path="*.html" verb="*"
preCondition="integratedMode" type="System.Web.StaticFileHandler" />
<remove name="BlockViewHandler"/>
<add name="BlockViewHandler" path="*" verb="*" preCondition="integratedMode" type="System.Web.HttpNotFoundHandler" />
</handlers>

I want to be able to request static .html files which are located in
the ~/Views folder.
Well you can. The marked answer is not entirely correct, although it gives a solution.
The reasoning in the marked answer is correct, it is web.config (BlockViewHandler setting to be specific) in the Views folder that prevents the files to be accessed directly. It is there for securing the views in Asp.Net MVC. But if you asked a question about serving these files directly then you likely have a valid reason to do so, like using AngularJS partial views (as in our case) where we do not want to duplicate the views folder with weird names.
So here is a very simple tweak you can do in the web.config file found in the Views folder, without compromising security of your asp.net mvc views. This will secure the .cshtml files as usual but leave your .html files alone.A
Change this
<add name="BlockViewHandler" path="*" verb="*" preCondition="integratedMode" type="System.Web.HttpNotFoundHandler" />
--to--
<add name="BlockViewHandler" path="*.cshtml" verb="*" preCondition="integratedMode" type="System.Web.HttpNotFoundHandler" />

Another alternate option is to insert an action method in any of the desired controller to serve the html file
public ActionResult MyHtml()
{
var result = new FilePathResult("~/Views/HtmlPage1.html", "text/html");
return result;
}
Access the html as http://yoursite/controller/MyHtml. You may extend this action method to accept the html file name as method/querystrign parameter and render the file at run time, e.g something like this.
public ActionResult MyHtml(string htmlPageName)
{
var result = new FilePathResult($"~/Views/{htmlPageName}.html", "text/html");
return result;
}

If you are planning to use inside view folder, above answers should be best but this answer may be useful for users who are migrating to asp.net mvc core. Placing files in wwwroot instead of views folder should make your html pages access easily as localhost/myfile.html

You can place it in the /Content folder.

Related

Include Scripts from Feature folder in ScriptBundle

I'm trying to include js files that are not part of the original ~/Scripts folder included in a MVC web project. Rather I have my script files inside of my Feature folder like: ~/Features/MyNewFeature/Scripts
However when running the app I get nothing but 404 errors when the request goes to find those js files. I'm not sure what I'm missing or if there's something that needs to be added to make this work. I know I've read that js files have to be in the Scripts folder but I'm having a hard time believing that since there's a way around not having your cshtml files inside a /Views folder.
bundles.Add(new ScriptBundle("~/bundles/mynewfeature")
.Include("~/Features/MyNewFeature/Scripts/Settings.js"));
Then to render in cshtml:
#Scripts.Render("~/bundles/mynewfeature")
So the problem was first starting once the/Views Web.config got moved to the Features folder. To fix the problem I was able to add a new handler that explicitly allows js files.
<system.webServer>
<handlers>
<remove name="BlockViewHandler" />
<add name="JavaScript" path="*.js" verb="GET, HEAD" type="System.Web.StaticFileHandler" />
<add name="BlockViewHandler" path="*" verb="*" preCondition="integratedMode" type="System.Web.HttpNotFoundHandler" />
</handlers>
</system.webServer>

Custom server control and Generic Web handler

I'm creating a custom server control which uploads files asynchronously to the server.
This solution uses flash element that posts the files to Generic Web handler aka ashx which then saves the posted file in a desired location.
It works grate, but with this approach I do need to create ashx file in each project, potentially, to handle the posts from the flash element.
What I would like to achieve is fully encapsulated server control that will use it's own ashx (or whatever can replace it) handler to upload the files.
Is it possible to do? Any ideas would be welcome.
Thanks.
You could include the handler within the class library containing the control and then only register it in web.config using the <httpHandlers> section:
<configuration>
<system.web>
<httpHandlers>
<add verb="*"
path="upload.ashx"
type="MyControl.MyUploadHandler.New, MyControl" />
</httpHandlers>
<system.web>
</configuration>
and if you are using IIS 7 Integrated pipeline mode to the <handlers> section:
<system.webServer>
<handlers>
<add name="UploadHandler"
verb="*"
path="upload.ashx"
type="MyControl.MyUploadHandler.New, MyControl" />
</handlers>
</system.webServer>
And if you are using ASP.NET 4.0 you could checkout the PreApplicationStartMethod infrastructure which allows you to dynamically register handlers:
[assembly: WebActivator.PreApplicationStartMethod(typeof(MyControl.StartUp), "PreApplicationStart")]

ASP.NET Basic Authentication for MIME Type files (None .aspx files)

I have to authenticate users (Basic Authentication) for accessing a None .aspx file against a datasource. I found articles and did it for .aspx files but as soon as I try to use it for my file **by adding file extention to IIS as a MIME or Compressed type file, the authentication windows keeps showing and dones't stop.
What Should I do?
P.S.1. I cannot change the authentication method with form auth or something else.
P.S.2. I cannot change my file type with ".aspx"
P.S.3. URL Re-Writing didn't solve the problem
P.S.4. I added handler to web.config to show the IIS that the new file extention is a script
<handlers>
<add name="NEW FORMAT" path="*.NXX" verb="GET,HEAD,POST,DEBUG" modules="IsapiModule"
scriptProcessor="C:\Windows\Microsoft.NET\Framework64\v4.0.30319\aspnet_isapi.dll"
resourceType="Either" requireAccess="Script" preCondition="classicMode,runtimeVersionv4.0,bitness64" />
</handlers>
You can use the location directive to constraint the access for the actual file:
http://msdn.microsoft.com/en-us/library/b6x6shw7(v=vs.100).aspx
And add the mime type if you really need it:
http://www.iis.net/ConfigReference/system.webServer/staticContent/mimeMap
!
Also you can create an ashx file to help you transmit all the files you require, adding a little more overhead but can provide a little more security.
Hope it helps.

ASP.NET MVC Routing - add .html extension to routes

i am pretty new to MVC and Routing and i was asked to modify an app to use diffrent url's.
a task that is a bit over me since i have no experience.
ok, lets talk a bit of code:
routes.MapRoute(
"CategoryBySeName", // Route name
"products/{SeName}", // URL with parameters
new { controller = "Catalog", action = "CategoryBySeName" }
);
this works as expected, but then the client wanted ".html" at the end of paths, so i changed:
"products/{SeName}", // URL with parameters
to:
"products/{SeName}.html", // URL with parameters
which fails ( IIS 404 page - MapRequestHandler)
it seems like iis is trying to load a physical file with that name instead of passing it to the application.
Similar: ASP.NET MVC Routing to start at html page (not answered, Not duplicate)
You have to force all request through the ASP.NET pipeline, and you can do that by adding only this single line to the web.config of your application:
<system.webServer>
<modules runAllManagedModulesForAllRequests="true" />
</system.webServer>
You're guess that an IIS handler is probably grabbing the request prior to MVC is likely correct.
Assuming IIS 7:
http://technet.microsoft.com/en-us/library/cc770990(v=ws.10).aspx
You need to edit the .html handler in IIS to use ASP.NET.
You can find it in the website properties under the home directory tab in app configuration in the mappings section in II6.
Something along the lines of (version may be different):
C:\windows\microsoft.net\framework\v4.0.30319\aspnet_isapi.dll is what you need to handle the .html files.
Changing the Application Pool from Classic to Integrated fixed the issue.
thank you guyz for your help.
Just add this section to Web.config, and all requests to the route/{*pathInfo} will be handled by the specified handler, even when there are dots in pathInfo. (taken from ServiceStack MVC Host Web.config example and this answer https://stackoverflow.com/a/12151501/801189)
<location path="route">
<system.web>
<httpHandlers>
<add path="*" type="System.Web.Handlers.TransferRequestHandler" verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" />
</httpHandlers>
</system.web>
<!-- Required for IIS 7.0 -->
<system.webServer>
<modules runAllManagedModulesForAllRequests="true" />
<validation validateIntegratedModeConfiguration="false" />
<handlers>
<add name="ApiURIs-ISAPI-Integrated-4.0" path="*" type="System.Web.Handlers.TransferRequestHandler" verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" preCondition="integratedMode,runtimeVersionv4.0" />
</handlers>
</system.webServer>
</location>

What is an .axd file?

What kind of purpose do .axd files serve?
I know that it is used in the ASP.Net AJAX Toolkit and its controls. I'd like to know more about it.
I tried Googling for it, but could not find getting basic information.
from Google
An .axd file is a HTTP Handler file. There are two types of .axd files.
ScriptResource.axd
WebResource.axd
These are files which are generated at runtime whenever you use ScriptManager in your Web app. This is being generated only once when you deploy it on the server.
Simply put the ScriptResource.AXD contains all of the clientside javascript routines for Ajax. Just because you include a scriptmanager that loads a script file it will never appear as a ScriptResource.AXD - instead it will be merely passed as the .js file you send if you reference a external script file. If you embed it in code then it may merely appear as part of the html as a tag and code but depending if you code according to how the ToolKit handles it - may or may not appear as as a ScriptResource.axd. ScriptResource.axd is only introduced with AJAX and you will never see it elsewhere
And ofcourse it is necessary
Those are not files (they don't exist on disk) - they are just names under which some HTTP handlers are registered.
Take a look at the web.config in .NET Framework's directory (e.g. C:\Windows\Microsoft.NET\Framework\v4.0.30319\Config\web.config):
<configuration>
<system.web>
<httpHandlers>
<add path="eurl.axd" verb="*" type="System.Web.HttpNotFoundHandler" validate="True" />
<add path="trace.axd" verb="*" type="System.Web.Handlers.TraceHandler" validate="True" />
<add path="WebResource.axd" verb="GET" type="System.Web.Handlers.AssemblyResourceLoader" validate="True" />
<add verb="*" path="*_AppService.axd" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" validate="False" />
<add verb="GET,HEAD" path="ScriptResource.axd" type="System.Web.Handlers.ScriptResourceHandler, System.Web.Extensions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" validate="False"/>
<add path="*.axd" verb="*" type="System.Web.HttpNotFoundHandler" validate="True" />
</httpHandlers>
</system.web>
<configuration>
You can register your own handlers with a whatever.axd name in your application's web.config. While you can bind your handlers to whatever names you like, .axd has the upside of working on IIS6 out of the box by default (IIS6 passes requests for *.axd to the ASP.NET runtime by default). Using an arbitrary path for the handler, like Document.pdf (or really anything except ASP.NET-specific extensions), requires more configuration work. In IIS7 in integrated pipeline mode this is no longer a problem, as all requests are processed by the ASP.NET stack.
An AXD file is a file used by ASP.NET applications for handling embedded resource requests. It contains instructions for retrieving embedded resources, such as images, JavaScript (.JS) files, and.CSS files. AXD files are used for injecting resources into the client-side webpage and access them on the server in a standard way.

Categories