Domanda

I would like to display a 404 not found error on directory browse instead of the standard 403 unauthorized message from asp.net but not for the files within. For example:

 www.somedomain.com/services             -  404 not found
 www.somedomain.com/services/test.asmx   -  200 ok

I tried to do a custom generic handler like so:

public class DirectoryBrowsingAttempt : IHttpHandler
{
    public void ProcessRequest(HttpContext context)
    {
        context.Response.StatusCode = 404;
    }

    public bool IsReusable
    {
        get
        {
            return true;
        }
    }
}

And in the under web.config:

 <handlers>
  <add name="NoAccess" verb="*" path="Services"  preCondition="integratedMode" type="Namespace.DirectoryBrowsingAttempt"/>
</handlers>

This will throw a 404 for the directory and the files within. Is there a way to avoid the 404 for the files?

È stato utile?

Soluzione

You just need to add a slash after the path. The only thing that I don't like about this though is sub-folders. You would have to add a specific config to each level of the directories.

Leaving it open, or adding an asterik as the end, will ignore all files in that path.

<handlers>
    <add name="NoAccess" verb="*" path="Services/"  preCondition="integratedMode" type="Namespace.DirectoryBrowsingAttempt"/>
</handlers>

Altri suggerimenti

I found a simple solution for my problem by adding a wildcard handler for files under the services folder which are then passed on to the System.Web.Script.Services.ScriptHandlerFactory handler

  <add name="Services" verb="*" path="Services/*"  preCondition="integratedMode" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
  <add name="ServicesNoAccess" verb="*" path="Services"  preCondition="integratedMode" type="System.Web.StaticFileHandler"/>

Also note that a generic handler is not required to throw a 404 for the directory. Instead make use of the System.Web.StaticFileHandler which works as a catch all handler.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top