Question

I have written a custom AuthorizeAttribute having an override of HandleUnauthorizedRequest. This override conditionally sets the response status code to 404 with:

var response = filterContext.HttpContext.Response;
response.StatusCode = 404;
response.ContentType = null;
response.End();

The problem is that the full response is:

HTTP/1.1 404 Not Found
Server: ASP.NET Development Server/10.0.0.0
Date: Mon, 24 Jan 2011 16:43:08 GMT
X-AspNet-Version: 4.0.30319
X-AspNetMvc-Version: 2.0
Cache-Control: private
Connection: Close
 

when I would like to send back the default 404 page. Something like:


Screenshot of the default ASP.NET 404 page


How do I do that?

Was it helpful?

Solution 2

What I ended up doing is setting the Result property of the filter context like this:

var response = filterContext.HttpContext.Response;
response.StatusCode = 404;
var viewData = new ViewDataDictionary();
viewData["Id"] = filterContext.HttpContext.Request.RequestContext.RouteData.Values["id"];
filterContext.Result = new ViewResult { ViewName = "NotFound", ViewData = viewData };
return;

where "NotFound" is an action of the controller containing a different action that was marked with my custom AuthorizeAttribute.

OTHER TIPS

What about: Create a custom 404 handler in Web.config as follows:

<customErrors mode="On">
<error statusCode="404" redirect="My404ErrorPage.aspx" />
</customErrors>

Now all 404 errors go to My404ErrorPage.aspx (or whatever you choose to name your error page) and you can also redirect to it at will.

Maybe "Response.WriteError(404);

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top