Niranjan Godbole Niranjan Godbole - 3 years ago 291
ASP.NET (C#) Question

How to hide server version for custom errors in mvc?

Error page displaying iis server versionHi I am developing web application in .net mvc. I am hiding server version using

<remove name="X-Powered-By" />
in customheaders. It works fine and i am able to hide iis version. This works for pages that exists only. Also i have implemented

<customErrors defaultRedirect="Errorpage.html" mode="On">
<error statusCode="500" redirect="~/Login/Index" />
<error statusCode="400" redirect="~/Login/Index" />

for custom errors. for example, if i try to access page that does not exists then i will be redirected to Errorpage.html but in this case server version is visible to users.

Below is my global.asax code.

protected void Application_Start()
MvcHandler.DisableMvcResponseHeader = true;

protected void Application_PreSendRequestHeaders()
Response.Headers.Set("Server", "");
Response.Headers.Remove("X-AspNet-Version"); //alternative to above solution
Response.Headers.Remove("X-AspNetMvc-Version"); //alternative to above solution

new custom error
May i know how can i fix this issue in either cases pages that exists and pages that does not exists! may i get some help to fix this? Any help would be greatly appreciated. Thank you.

Answer Source

You can create a custom error page for 404 and add this to your web.config file.

<error statusCode="404" redirect="~/Home/PageNotFound" />

Where PageNotFound is your action in HomeController which returns view.

Now open your Global.asax.cs file to Application_Start, and add this code at the top:

MvcHandler.DisableMvcResponseHeader = true;

you can eliminate the "Server" header by adding a handler to PreSendRequestHeaders event like this:

protected void Application_PreSendRequestHeaders(object sender, EventArgs e)
    HttpApplication app = sender as HttpApplication;
    if (app != null &&
        app.Context != null)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download