1
votes

I am using httpErrors in my web.config and have the following:

<error statusCode="404" subStatusCode="1" responseMode="Redirect" path="http://www.somewhere-else.com" />

Doing the following in a custom action result, works fine:

Response.StatusCode = 404;
Response.SubStatusCode = 1;

But the code that determines whether the 404 redirect is necessary is a bit further down the stack so rather than returning an actionresult, I woul prefer to throw an exception and halt further execution.

For error entries in httpErrors without a subStatusCode, I can throw the appropriate HttpException and it works as expected:

throw new HttpException(400, "Bad Request");

But I need the subStatusCode. I have tried setting Response.SubStatusCode before throwing an HttpException but it gets ignored and the default 404 error page is shown.

Any way around this?

(btw, I know subStatusCode is only internal and not exposed to client)

1

1 Answers

0
votes

I realize this question is a bit old, bit figured I'd post an answer that I have come across that seems to work well enough for me. Using Asp.Net MVC 5.2, I throw an HttpException using the following:

throw new HttpException((int) HttpStatusCode.Unauthorized, "Context required", 12)

Then, in my global.asax.cs error handler:

protected void Application_Error()
{
    var exception = Server.GetLastError();
    var httpException = exception as HttpException; 

    if (httpException != null)
    {
        Context.Response.StatusCode = httpException.GetHttpCode();
        Context.Response.SubStatusCode = httpException.ErrorCode;
        Context.Server.ClearError();
    }
}  

Somewhat hackish, but it suits my needs..