I want to run my httphandler, when some user get access to image file with extentions like png, jpeg, gif and other. But i get eror 404 when i try to path. I think what server try find file on a disk, but i want use alias for access to file in my handler and newer access for real phisical file path.
Example config file:
<configuration>
<system.web>
<compilation debug="true" targetFramework="4.0" />
<httpHandlers>
<add verb="GET,HEAD" path="*.jpg" type="Startup.Shop.ImageHandler, Startup.Shop" validate="false"/>
</httpHandlers>
<authorization>
<allow users="*" />
</authorization>
</system.web>
<system.webServer>
<handlers>
<add name="ImageHandlerfor JPG" path="*.jpg" verb="GET" type="Startup.Shop.ImageHandler, Startup.Shop" resourceType="Unspecified" />
<add name="ImageHandler for GIF" path="*.gif" verb="GET" type="Startup.Shop.ImageHandler, Startup.Shop" resourceType="Unspecified" />
<add name="ImageHandler for BMP" path="*.bmp" verb="GET" type="Startup.Shop.ImageHandler, Startup.Shop" resourceType="Unspecified" />
<add name="ImageHandler for PNG" path="*.png" verb="GET" type="Startup.Shop.ImageHandler, Startup.Shop" resourceType="Unspecified" />
</handlers>
</system.webServer>
/configuration>
Example handler class:
public class ImageHandler : IHttpHandler, IRouteHandler
{
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/plain";
context.Response.Write("Hello World");
}
public bool IsReusable
{
get
{
return false;
}
}
public IHttpHandler GetHttpHandler(RequestContext requestContext)
{
return this;
}
}
And more - iis server configurated as classic mode
If you're in classic mode, then asp.net won't get called by IIS unless IIS knows the file type that should get mapped. In your IIS control panel, you should be able to configure the file types handled by ASP.NET. Otherwise, it's going to assume that a file type is for a physical file, which it can't find on the file system.
Related
I create an API to send data from server to client using ASP.NET.
I am using this guide: https://www.c-sharpcorner.com/article/how-to-send-data-from-android-to-sql-server-using-restful-ap/.
When I try to access the Handler.ashx I get ERR_CONNECTION_RESET error and I don't understand the reason.
web.config file:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<!-- To customize the asp.net core module uncomment and edit the following section.
For more info see https://go.microsoft.com/fwlink/?linkid=838655 -->
<system.webServer>
<handlers>
<remove name="aspNetCore" />
<add name="aspNetCore" path="*.ashx" verb="*" modules="AspNetCoreModuleV2" resourceType="Unspecified" />
</handlers>
<aspNetCore processPath="%LAUNCHER_PATH%" arguments="%LAUNCHER_ARGS%" stdoutLogEnabled="false" stdoutLogFile=".\logs\stdout" hostingModel="InProcess" />
</system.webServer>
<connectionStrings>
<add name="ConString" connectionString="Data Source=DESKTOP-1QIGJNA;Initial Catalog=tests;Integrated Security=True" providerName="System.Data.SqlCliesnt" />
</connectionStrings>
</configuration>
Handler.ashx:
<%# WebHandler Language="C#" Class="Handler" %>
using System;
using System.Web;
using JsonServices;
using JsonServices.Web;
namespace RESTful_API
{
public class Handler: JsonHandler
{
public Handler()
{
this.service.Name = "RESTful_API";
this.service.Description = "JSON API for android appliation";
InterfaceConfiguration IConfig = new InterfaceConfiguration("RestAPI", typeof(ISAPI), typeof(SAPI));
this.service.Interfaces.Add(IConfig);
}
}
}
On my site, I want to disallow HTTP HEAD requests and have them answered with the 405 status code (Method not allowed). To achieve this I have the following in my web.config file:
<system.webServer>
<modules runAllManagedModulesForAllRequests="true">
<remove name="TelemetryCorrelationHttpModule" />
<add name="TelemetryCorrelationHttpModule" type="Microsoft.AspNet.TelemetryCorrelation.TelemetryCorrelationHttpModule, Microsoft.AspNet.TelemetryCorrelation" preCondition="integratedMode,managedHandler" />
<remove name="ApplicationInsightsWebTracking" />
<add name="ApplicationInsightsWebTracking" type="Microsoft.ApplicationInsights.Web.ApplicationInsightsHttpModule, Microsoft.AI.Web" preCondition="managedHandler" />
</modules>
<handlers>
<clear />
<add name="DenyHead" path="*" verb="HEAD" type="System.Web.HttpMethodNotAllowedHandler" />
<add name="DebugAttachHandler" path="DebugAttach.aspx" verb="DEBUG" type="System.Web.HttpDebugHandler" preCondition="integratedMode,runtimeVersionv4.0" />
<add name="StaticFile" path="*" verb="*" modules="StaticFileModule" resourceType="Either" requireAccess="Read" />
<add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="GET,POST,DEBUG" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
</handlers>
<security>
<requestFiltering allowDoubleEscaping="true">
<verbs allowUnlisted="false">
<add verb="GET" allowed="true" />
<add verb="POST" allowed="true" />
<add verb="HEAD" allowed="true" />
<add verb="DEBUG" allowed="true" />
</verbs>
</requestFiltering>
</security>
</system.webServer>
Unfortunately, this doesn't work - I'm receiving bog-standard 404s instead.
Enabling failed request tracing yields the following:
20 HANDLER_CHANGED OldHandlerName
NewHandlerName DenyHead
NewHandlerType System.Web.HttpMethodNotAllowedHandler
...
61 AspNetPipelineEnter Data1 <Application_BeginRequest in my ASP.NET application>
...
135 HANDLER_CHANGED OldHandlerName System.Web.HttpMethodNotAllowedHandler
NewHandlerName System.Web.Mvc.MvcHandler
...
169 MODULE_SET_RESPONSE_ERROR_STATUS Notification EXECUTE_REQUEST_HANDLER
HttpStatus 404
This seems to show that the DenyHead handler is somehow being replaced/overridden by my MVC application, but there's no code in my app that does anything of the sort.
I've tried alternative recommendations such as the answers here, but they give the same result.
Request filtering isn't an option because the status code it returns is not configurable (it always returns a 404).
Action filters aren't an option because they won't be hit for static content, and I don't want to send everything through the MVC pipeline.
You can create action filter, and check for request method. If it is "HEAD", you can reject request by settings Result property on filterContext and set statuscode to 405 method not allowed.
Or You can check above logic for Application_BeginRequest in Global.aspx and do the same.
I wouldn't use IIS configuration as it gets you dependant on IIS, even though you might already be. Using a filter removes that dependency, just like that:
public class VerbFilter : IAsyncActionFilter
{
public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
{
if (context.HttpContext.Request.Method == "HEAD")
{
context.Result = new StatusCodeResult(405);
}
else
{
await next();
}
}
}
After following all the guides, SO pages and troubleshooting pages I can find I'm finally out of ideas.
I've got Glimpse working fine on my local dev server, but when I deploy my ASP.net (MVC5) app to my remote server it doesn't work - at all. /glimpse.axd gives a 404 with both LocalPolicy and ControlCookiePolicy set to ignore, and with a custom security policy that returns On in all cases. My understanding is that with ControlCookiePolicy disabled, I shouldn't need to go to /glimpse.axd to enable it - but I'm not seeing the glimpse icon on the remote server either.
Even if I go to the remote server and browse localhost to /glimpse.axd I still get a 404.
My web.config looks like this:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections>
<section name="glimpse" type="Glimpse.Core.Configuration.Section, Glimpse.Core" />
</configSections>
<system.web>
<compilation debug="false" />
<httpRuntime targetFramework="4.5.1" relaxedUrlToFileSystemMapping="true" />
</system.web>
<system.webServer>
<modules runAllManagedModulesForAllRequests="true">
<remove name="FormsAuthentication" />
</modules>
<urlCompression doDynamicCompression="true" dynamicCompressionBeforeCache="false" />
</system.webServer>
<glimpse defaultRuntimePolicy="On" endpointBaseUri="~/Glimpse.axd">
<logging level="Trace" />
<runtimePolicies>
<ignoredTypes>
<add type="Glimpse.AspNet.Policy.LocalPolicy, Glimpse.AspNet" />
<add type="Glimpse.Core.Policy.ControlCookiePolicy, Glimpse.Core" />
</ignoredTypes>
</runtimePolicies>
</glimpse>
</configuration>
This is the version off the remote server (after transform). I've trimmed it a little to remove sections like appSettings.
My GlimpseSecurityPolicy.cs looks like this:
// Uncomment this class to provide custom runtime policy for Glimpse
using Glimpse.AspNet.Extensions;
using Glimpse.Core.Extensibility;
namespace RationalVote
{
public class GlimpseSecurityPolicy:IRuntimePolicy
{
public RuntimePolicy Execute(IRuntimePolicyContext policyContext)
{
return RuntimePolicy.On;
}
public RuntimeEvent ExecuteOn
{
// The RuntimeEvent.ExecuteResource is only needed in case you create a security policy
// Have a look at http://blog.getglimpse.com/2013/12/09/protect-glimpse-axd-with-your-custom-runtime-policy/ for more details
get { return RuntimeEvent.EndRequest | RuntimeEvent.ExecuteResource; }
}
}
}
The real one does an actual check, but I get the same issue with the policy above.
I cannot seem to find any trace output anywhere on the remote server, it is logging fine on my local machine.
I am deploying using the Visual Studio publish to web feature, and I've verified that the Glimpse.Core.dll is in the bin folder.
I can't see anything in the event log that is relevant.
I've also added <add namespace="Glimpse.Mvc.Html" /> to the namespaces block of the web.config in the views folder.
I tried putting #Html.GlimpseClient() in the _Layout.cshtml file just above </body> but this renders nothing.
Anybody got any ideas?
If the glimpse.axd is returning a 404 then this means the Glimpse resource handler is not registered.
If the web.config content you show above is not trimmed to much, then it is normal that Glimpse won't do much as the Glimpse HttpModule and the Glimpse HttpHandler are not registered in the system.web and/or the system.webserver sections like this
<system.web>
<httpModules>
<add name="Glimpse" type="Glimpse.AspNet.HttpModule, Glimpse.AspNet"/>
</httpModules>
<httpHandlers>
<add path="glimpse.axd" verb="GET" type="Glimpse.AspNet.HttpHandler, Glimpse.AspNet"/>
</httpHandlers>
</system.web>
<system.webServer>
<validation validateIntegratedModeConfiguration="false"/>
<modules>
<add name="Glimpse" type="Glimpse.AspNet.HttpModule, Glimpse.AspNet" preCondition="integratedMode"/>
</modules>
<handlers>
<add name="Glimpse" path="glimpse.axd" verb="GET" type="Glimpse.AspNet.HttpHandler, Glimpse.AspNet" preCondition="integratedMode" />
</handlers>
</system.webServer>
Maybe your transform removed to much from the local web.config?
This is my first Service in ServiceStack.
public class UserServiceHost : AppHostBase
{
public UserServiceHost() : base("UserServiceHost", typeof(UserService).Assembly) { }
public override void Configure(Funq.Container container)
{
// Configure Application
}
}
protected void Application_Start(object sender, EventArgs e)
{
new UserServiceHost().Init();
}
Very simple. The file UserService is the same project and directory of the Global.Asax.
When I run the project the metadata page is not displayed. The directory listing of the site is displayed.
In fact when I insert the /metadata I receive a 404.
My project is a ASP.Net Web Application. I have included ServiceStack, everything seems ok.
What am I doing wrong ?
Thanks in advance
Please adjust your web.config like following:
<system.web>
<httpHandlers>
<add path="*" type="ServiceStack.WebHost.Endpoints.ServiceStackHttpHandlerFactory, ServiceStack" verb="*"/>
</httpHandlers>
</system.web>
<!-- Required for IIS 7.0 (and above?) -->
<system.webServer>
<validation validateIntegratedModeConfiguration="false" />
<handlers>
<add path="*" name="ServiceStack.Factory" type="ServiceStack.WebHost.Endpoints.ServiceStackHttpHandlerFactory, ServiceStack" verb="*" preCondition="integratedMode" resourceType="Unspecified" allowPathInfo="true" />
</handlers>
</system.webServer>
I've got a virtual path provider (VPP) that serves simple aspx pages.
The problem lies when I introduce static references such as *.css, *.jpg files, etc ...
I noticed my VPP is capturing these requests. I don't want this to happen.
I want the normal System.Web.StaticFileHandler to handler these requests.
I've added the following in my web config:
<system.web>
<httpHandlers>
<add verb="GET,HEAD" path="*.css" type="System.Web.StaticFileHandler" />
<add verb="GET,HEAD" path="*.js" type="System.Web.StaticFileHandler" />
<add verb="GET,HEAD" path="*.jpg" type="System.Web.StaticFileHandler" />
<add verb="GET,HEAD" path="*.gif" type="System.Web.StaticFileHandler" />
</httpHandlers>
</system.web>
But my VPP still handles these requests.
Any ideas?
cheers in advance
I guess the VirtualPathProvider is invoked for every request. You'll have to override the FileExists method to tell the runtime whether the request is handled by the VirtualPathProvider or not.