WebApi2 + CORS + OWIN fails IIS 8.5 - iis

I have my application working well running on VS 2013, but when I publish on IIS 8.5 CORS stops working due:
No 'Access-Control-Allow-Origin' header is present on the requested resource.
I tried this in the web.config, but still the same:
<httpprotocol>
<customheaders>
<add name="Access-Control-Allow-Origin" value="*"></add>
</customheaders>
</httpprotocol>
The error occurs when I try to authenticate:
XMLHttpRequest cannot load http://<myurl>/token
I have this configuration for OWIN, and again, Its works well running locally:
app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);
app.UseOAuthBearerTokens(OAuthOptions);

I solve the issue. I was getting a 500 error that Chrome does't intercept. After use Feddler I was able to see what really was going on with my request, and I did intecept the right Response Error.
Important: If you get any error at the server with CORS It will respond you as No 'Access-Control-Allow-Origin' header is present on the requested resource., I don't know why, but makes stuff difficult to trace.

Related

HTTP Error 500.19 - IIS and MIME Type not working in windows10?

I am trying to run my asp.net mvc website on the IIS. I got the following error:
HTTP Error 500.19 - Internal Server Error The requested page cannot be
accessed because the related configuration data for the page is
invalid.
I use IIS through IIS manager and when I try to configure MIME Types in IIS Manager, I got the following config error:
There was an error while performing this operation. Error: Cannot add
duplicate collection entry of type 'mimeMap' with unique key attribute
'fileExtension' set to '.woff2'.
As a result of my detailed research, this problem occurs on IIS 7.5. How to get rid of this errors and run my web page on IIS?
At first, try to install iis rewrite module to told IIS my custom web.config is not failure or faulty. If it's not fix the problem, I suggest another solution particularly for your problem. Delete your .wolf2 config from your web.config file. For example;
<staticContent>
<mimeMap fileExtension=".woff2" mimeType="application/font-woff2" />
</staticContent>
Delete mimeMap row which has .woff2 file extension from the staticContent. It would fix your problem because this error says that I already have .wolf2 in my config file but you trying to add one more.

HTTP Error 405.0 - Method Not Allowed in IIS Express

When issuing a perfectly cromulent verb to a local IIS Express web-site under Visual Studio 2013:
CROMULENT http://localhost:7579/Handler.ashx HTTP/1.1
Host: localhost:7579
the server responds with the error:
HTTP/1.1 405 Method Not Allowed
Allow: GET, HEAD, OPTIONS, TRACE
That is a request to a "generic handler" (i.e. .ashx). If if i try again to a static resource:
SCHWIFTY http://localhost:7579/Default.htm HTTP/1.1
Host: localhost:7579
the server responds with the error:
HTTP/1.1 405 Method Not Allowed
Allow: GET, HEAD, OPTIONS, TRACE
This is all by way to trying to use HTTP verbs:
DELETE http://localhost:7579/Handler.ashx HTTP/1.1
Host: localhost:7579
HTTP/1.1 405 Method Not Allowed
Allow: GET, HEAD, OPTIONS, TRACE
PUThttp://localhost:7579/Handler.ashx HTTP/1.1
Host: localhost:7579
HTTP/1.1 405 Method Not Allowed
Allow: GET, HEAD, OPTIONS, TRACE
This question has been asked to death, sometimes by me. But nobody has ever come up with a solution.
</Question>
Microsoft's Bug
The problem, fundamentally, is that Microsoft ships IIS and IISExpress broken by default. Rather than handling HTTP verbs, as a web-server is required to do, they don't handle verbs.
This can most easily be seen when managing full IIS running on Windows Server. Pick any of the built-in handlers (e.g. the cshtml handler), and you can see that someone thought it would be hilarious if it only worked with GET, HEAD, POST, and DEBUG verbs:
rather than correctly implementing support for HTTP in an HTTP server.
The question becomes:
why exactly doesn't it work
how exactly to fix it
how to fix it in IIS Express (without any management tools)
why it continues to be shipped, year after year, broken
Question 1. Why doesn't it work?
The first question is why doesn't it work. Let's look at an IIS server where we've removed every handler except the basic Static file handler:
The handler is configured to all all verbs:
The only handler left is set to allow any verb. Yet if we issue a request to the web server we get the error:
DELETE http://scratch.avatopia.com/ HTTP/1.1
Host: scratch.avatopia.com
HTTP/1.1 405 Method Not Allowed
Allow: GET, HEAD, OPTIONS, TRACE
Server: Microsoft-IIS/7.5
Why is this happening?
Why didn't it work? Where is the configuration option that says:
GET
HEAD
OPTIONS
TRACE
because the server itself is saying those are the only supported verbs.
Yet if we change it to a GET it works fine:
GET http://scratch.avatopia.com/ HTTP/1.1
User-Agent: Fiddler
Host: scratch.avatopia.com
HTTP/1.1 200 OK
Content-Type: text/html
Question 2. How to fix it?
The common wisdom is to remove WebDAV. Nobody knows what WebDAV is, how it could be a problem, why it is a problem, or why it exists if it only causes problems. WebDAV can be removed as a handler from the IIS administration user interface:
which is identical to adding a remove entry from the handlers section in web.config (the UI itself adds the entry to web.config for you):
<system.webServer>
<handlers>
<remove name="WebDAV" />
</handlers>
</system.webServer>
Except this doesn't work. So how do we fix it?
Starting with IIS it seems that WebDAV has become even more of a virus. Rather than simply disabling it as a handler, you have to completely install or remove it as a module:
<system.webServer>
<modules>
<remove name="WebDAVModule" />
</modules>
<handlers>
<remove name="WebDAV" />
</handlers>
</system.webServer>
That sounds like a reason idea, except in my test case, on IIS 7.5, WebDAV is both not installed, and removed as a module:
HTTP/1.1 405 Method Not Allowed
Allow: GET, HEAD, OPTIONS, TRACE
Server: Microsoft-IIS/7.5
X-Powered-By: ASP.NET
Date: Tue, 10 May 2016 19:19:42 GMT
Content-Length: 0
So, if we can figure out how to solve the problem, we can answer question number two.
Question 3. How to fix it in IIS Express
Starting with Visual Studio 20131, Visual Studio no longer uses a mini web-server called Cassini. It uses a portable install of IIS Express itself (i.e. IIS Express Windows feature doesn't need to be installed).
Most of the above fix (attempts) (fail) in IIS. But nobody has dealt with them in IIS Express of Visual Studio 2013 (which is how this question is different from any others).
Question 4. Why does this keep happening?
It's been over 15 years, and this still keeps happening. There must be a good reason why IIS does not function as a web-server. But what is it? I've not been able to find any knowledge base article, or blog post, explaining why the IIS team refuses to function correctly.
Bonus Reading
The most popular Stackoverflow question for this problem: ASP.NET Web API - PUT & DELETE Verbs Not Allowed - IIS 8
Research Effort
HTTP Error 405.0 - Method Not Allowed, with POST (no answer, php)
HTTP Error 405.0 - Method Not Allowed (no answer)
POST verb not allowed (php)
HTTP Error 405.0 - Method Not Allowed in ASP.net MVC5 (no answer, mvc)
JQuery File Uploader = error 405 IIS8.5 (jquery no answer)
IIS 7.5 405 Method Not Allowed for PUT from StaticFileModule (no answer, static module, iis)
The HTTP verb POST used to access path is not allowed ("don't use verbs")
http error 405 method not allowed error with web.API (uninstall WebDAV; already isn't)
Handling Perl IIS 7.5 (perl)
HTTP Error 405.0 - Method Not Allowed using Jquery ajax get (ajax)
What causes an HTTP 405 "invalid method (HTTP verb)" error when POSTing a form to PHP on IIS? (iis6, ftp, php)
http://forums.asp.net/t/1648594.aspx ("have you tried pinging your computer")
Angular $resource POST/PUT to WebAPI 405 Method Not Allowed (try removing WebDAV handlder and WebDAV module)
Http Error 405.0 - method not allowed iis 7.5 module staticfilemodule (no solution)
Unable to set up WebDAV with IIS 7 *(trying to setup webdav)*
Android SOAP request is returning HTTP Response 405 (no solution)
wcf service doesn't allow POST (wcf)
WebAPI Delete not working - 405 Method Not Allowed (WebAPI; remove WebDAV)
I seem to pick up on a bit of frustration in the question, so the actual question is a bit unclear. What specifically is it that you are trying, but failing, to do? What do you expect of the answer?
Anyway, based on this comment in the question:
This is all by way to trying to use HTTP verbs:
and the corresponding samples involving a generic handler, I'll take a stab at showing what is needed to make it possible to PUT and DELETE a generic handler.
In order to allow PUT and DELETE on a generic handler, you must allow it in the web.config of the application. To do that you should register a handler for *.ashx as follows:
<system.webServer>
<handlers>
<add name="SimpleHandlerFactory-Integrated-WithPutDelete"
path="*.ashx"
verb="GET,HEAD,POST,DEBUG,PUT,DELETE"
type="System.Web.UI.SimpleHandlerFactory"
resourceType="Unspecified"
requireAccess="Script"
preCondition="integratedMode" />
</handlers>
</system.webServer>
Depending on how you originally set up the web site/application, there may or may not be a handler registered for type="System.Web.UI.SimpleHandlerFactory" in your web.config file. If there is one, you should be able to just modify that entry and add the verbs you want to allow.
You'll note that this entry has the preCondition="integratedMode". This should, I believe, work when debugging in Visual Studio using IIS Express. In a real IIS deployment, the handler registration may need to be modified to match the application pool that will run the application. For an application running in classic mode (not integrated), it would look something like this (not tested so may be wrong):
<system.webServer>
<handlers>
<add name="SimpleHandlerFactory-ISAPI-4.0_64bit-WithPutDelete"
path="*.ashx"
verb="GET,HEAD,POST,DEBUG,PUT,DELETE"
modules="IsapiModule"
scriptProcessor="%windir%\Microsoft.NET\Framework64\v4.0.30319\aspnet_isapi.dll"
preCondition="classicMode,runtimeVersionv4.0,bitness64"
responseBufferLimit="0" />
</handlers>
</system.webServer>
The exact details would depend on the framework version an bit-ness of the application pool.
If you are debugging in Visual Studio using IIS Express, you should have a look at the applicationhost.config which sets up a lot of the defaults regarding IIS Express. It is located in:
My Documents\IISExpress\config
The untested handler registration above for a classic pipeline application pool is a slight modification of a handler registration in that file. There are in my environment 6 separate entries for *.ashx, with varying preconditions, in that file.
It might be a good idea to explicitly remove all of these in your web.config if you want to have your own registration which allows PUT and DELETE. Not all of them would actually be active/registered at the same time since the preconditions are (I suppose) mutually exclusive, but at least for me it works to just remove them all, one after the other. In my environment the section with the removes looks like this:
<remove name="SimpleHandlerFactory-ISAPI-4.0_64bit"/>
<remove name="SimpleHandlerFactory-ISAPI-4.0_32bit"/>
<remove name="SimpleHandlerFactory-Integrated-4.0"/>
<remove name="SimpleHandlerFactory-Integrated"/>
<remove name="SimpleHandlerFactory-ISAPI-2.0"/>
<remove name="SimpleHandlerFactory-ISAPI-2.0-64"/>
Hope this shines at least a bit of light into dark places!
okay so i ran into this same exact problem on IIS 7.5 when trying to PUT or DELETE it returned a 405.
i was specifically trying to setup a MEAN stack with IISnode module. when accessing the static HTML file IIS was serving up i was able to GET and PUSH but not PUT or DELETE.
-- the problem --
i believe that the issue is with IIS server itself. take a look at this post here:
https://blogs.msdn.microsoft.com/saurabh_singh/2010/12/10/anonymous-put-in-webdav-on-iis-7-deprecated/
https://support.microsoft.com/en-us/kb/2021641
it appears that IIS no longer allows Anonymous PUT or DELETE
so in the end i just went with a nodejs webserver instead
-- however --
i have not tried this but perhaps you might want to look into modifying the IIS system config file itself called the ApplicationHost.config located here:
C:\Windows\System32\inetsrv\config
make sure to use notepad with administrator privileges
let me know how it goes and i might try and do this later when i have time
There is a lot of talk about removing WebDAV and that will fix the problem - but if you're wondering what WebDAV is and what its used for, check out this page:
https://www.cloudwards.net/what-is-webdav/
Holy Damn, many research these 2 days....
No WebDav installed, no typical handler modifications (SimpleHandlerFactory, ExtensionlessUrl)
For those using any PHP Frameworks just as: Laravel, CakePHP etc
I couldn't make IIS Failed Tracing Logs work, so...
All I did was, modify PHP handler [MODIFY: php-X_VERSION]:
<handlers>
<remove name="php-X_VERSION" />
<add name="php-X_VERSION" path="*.php" verb="GET,HEAD,POST,PUT,DELETE" modules="FastCgiModule" scriptProcessor="D:\Program Files\PHP\X_VERSION\php-cgi.exe" resourceType="Either" requireAccess="Script" />
</handlers>
I have no WebDAV installed, and am running IIS Express from VS2019. After some digging, I came upon the applicationhost.config file used by IIS Express, and ended up with a solution by changing my own project web.config file. In the system.webServer/handlers section, add the following:
<system.webServer>
<handlers>
<remove name="PageHandlerFactory-ISAPI-4.0_64bit"/>
<remove name="PageHandlerFactory-ISAPI-4.0_32bit"/>
<remove name="PageHandlerFactory-Integrated-4.0"/>
<remove name="PageHandlerFactory-Integrated"/>
<remove name="PageHandlerFactory-ISAPI-2.0"/>
<remove name="PageHandlerFactory-ISAPI-2.0-64"/>
<add name="PageHandlerFactory-ISAPI-4.0_64bit" path="*.aspx" verb="GET,HEAD,POST,DEBUG,PUT" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework64\v4.0.30319\aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv4.0,bitness64" responseBufferLimit="0" />
<add name="PageHandlerFactory-ISAPI-4.0_32bit" path="*.aspx" verb="GET,HEAD,POST,DEBUG,PUT" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework\v4.0.30319\aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv4.0,bitness32" responseBufferLimit="0" />
<add name="PageHandlerFactory-Integrated-4.0" path="*.aspx" verb="GET,HEAD,POST,DEBUG,PUT" type="System.Web.UI.PageHandlerFactory" preCondition="integratedMode,runtimeVersionv4.0" />
<add name="PageHandlerFactory-Integrated" path="*.aspx" verb="GET,HEAD,POST,DEBUG,PUT" type="System.Web.UI.PageHandlerFactory" preCondition="integratedMode,runtimeVersionv2.0" />
<add name="PageHandlerFactory-ISAPI-2.0" path="*.aspx" verb="GET,HEAD,POST,DEBUG,PUT" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework\v2.0.50727\aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv2.0,bitness32" responseBufferLimit="0" />
<add name="PageHandlerFactory-ISAPI-2.0-64" path="*.aspx" verb="GET,HEAD,POST,DEBUG,PUT" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework64\v2.0.50727\aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv2.0,bitness64" responseBufferLimit="0" />
</handlers>
</system.webServer>
All this does, is it adds the word "PUT" to the verb attribute of each handler.
I also have to add that I am working on an older project and created the API endpoints with *.aspx files, which is why other solutions found googling did not work. So if you are using VS2019 and get the error 405.0 - Method not Allowed and you already removed WebDAV and expose your API with .aspx files this might work.

CORS problems in WebAPI hosted in IIS

I'm trying to implement an application that uses the same Token Based Authentication mechanism demonstrated in this really awesome example by Taiseer Joudeh.
In my application I kept encountering Cors problems. In some configurations I would get a 500 error on the Preflight (OPTIONS) request for the POST to get the token or I could get the token but then get a 404 error on the preflight request for the GET request to the actual API call with the Bearer token.
One difference was that Taiseer's code was setup to host in IISExpress (or Azure) and mine is hosted on Local IIS (running on Windows 7 at the moment).
On a hunch I tried hosting his API under Local IIS and I found the exact same problem. (500 error on the preflight request for the token and it looks like the actual API will work properly)
From what I've been reading it seems like this may be some conflict between the modules and handlers in IIS and the Cors implementation in WebApi but Taiseer's implementation works when hosted in Azure so perhaps it is a difference in the version of IIS (I'm currently running under Windows 7).
How can I sort out what is causing the problem?
The root of the problem
The Token action is not hosted in a controller but is instead built in somewhere in the lower level plumbing. The only access to the mechanism is through the override method GrantResourceOwnerCredentials() in the class that extends OAuthAuthorizationServerProvider. (In our case is ApplicationOAuthProvider.cs).
GrantResourceOwnerCredentials() does have the context available but it is not called as part of the PreFlight request so you have no way to insert the appropriate PreFlight response headers for CORS.
The solution
We eventually settled on the following solution. I'm not a big fan of it because it forces these headers into every response but at least it works.
The solution was to override Application_PreSendRequestHeaders() method in Global.asax to insert the appropriate headers.
Global.asax.cs
void Application_PreSendRequestHeaders(Object sender, EventArgs e)
{
var origin = Request.Headers.Get("Origin");
var validOrigins = ConfigurationManager.AppSettings["allowedCorsOrigins"].Split(',');
if(validOrigins.Any(o => o == origin))
{
Response.Headers.Set("Access-Control-Allow-Origin", origin);
Response.Headers.Set("Access-Control-Allow-Credentials", "true");
Response.Headers.Set("Access-Control-Allow-Headers", "Content-Type, Accept, Authorization, withcredentials, Prefer");
Response.Headers.Set("Access-Control-Expose-Headers", "Claims, *");
Response.Headers.Set("Access-Control-Max-Age", "600");
Response.Headers.Set("Access-Control-Allow-Methods", "GET,PUT,POST,DELETE,OPTIONS");
}
}
This requires the following web.config entries:
web.config
<configuration>
<appSettings>
<add key="allowedCorsOrigins" value="http://www.allowedsite1.net,http://localhost:22687" />
<add key="allowedCorsMethods" value="get, post, put, delete, options, batch" />
<add key="allowedCorsHeaders" value="*" />
</appSettings>
...
</configuration>
The reason for the loop to search for the valid origins is that you can't respond with a list of allowed origins...
This solved most of the problems with one exception (If I recall correctly was problems with PUT and DELETE verbs). This required removing the "ExtensionlessUrlHandler-Integrated-4.0" and re-adding it with a path and verb in the handlers section of the web.config.
web.config (2nd change)
<system.webServer>
<handlers>
<remove name="ExtensionlessUrlHandler-Integrated-4.0" />
<add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="*" type="System.Web.Handlers.TransferRequestHandler" preCondition="" />
</handlers>
....
</system.webServer>
Useful links related CORS
Really good description of PreFlight for CORS
Excellent Sample Application using Token Auth
It is not the IdentityServer you are using but it could be the same problem. Regarding to the IdentityServer´s Github page you have to activate RAMMFAR (runAllManagedModulesForAllRequests) for your application when running under the IIS.
<system.webServer>
<modules runAllManagedModulesForAllRequests="true">
</modules>
</system.webServer>
I had this same issue, I did everythin as suggested by Mr. Tom hall. But still chrome reported no Access-control-allow-origin header is present.. after inspecting with fidler i realized that my request goes through a proxy server and my proxy server is handling the preflight options request..
So in "internet options" i removed the proxy server and found out that everything is working...!!!

Customize error 400 (Bad Request) avoid IIS-8 intercepting it

The request is intercepted by the IIS, and it never hits my application.
I want that my Error Handling to manage this error, not IIS. Is this possible?
I've tried many things, including these:
In my Web.config: <httpErrors errorMode="DetailedLocalOnly" existingResponse="PassThrough"></httpErrors>
Also this configuration:
<httpErrors errorMode="DetailedLocalOnly" existingResponse="PassThrough">
<remove statusCode="400"/>
<error statusCode="400" path="http://www.google.com" responseMode="Redirect"/>
</httpErrors>
From the MSDN (IIS 7, nothing on IIS 8 documentation):
You cannot customize the following HTTP error messages: 400, 403.9,
411, 414, 500, 500.11, 500.14, 500.15, 501, 503, and 505.
Here we can replicate the error:
https://stackoverflow.com/ + %%% (you should copy the entire link, with the invalid characters included).
It seems that you are out of luck with this as the following thread already shows: https://serverfault.com/questions/257680/properly-handle-iis-request-with-percent-sign-in-url
One possible solution is to handle this error code at your load balancer (which of course will not be IIS based).
See my answer to
Custom error page configured in IIS for code 400 (bad request) is ignored
in short the redirect with <httpErrors errorMode="Custom" ... works already also for HTTP 400 / bad request and one can customize it except for the errors blocked by the IIS Kernel (for example bad URL)
I am not sure about the version of IIS where it started working. I tested it on IIS 10.
The example https://stackoverflow.com/% still won't work, but
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
will work as expected (it won't be blocked from the IIS Kernel)

Remove Server Response Header IIS 8.0 / 8.5

How can we remove the server header response in IIS 8.0/8.5?
My current server report:
Microsoft-IIS/8.0
Microsoft-IIS/8.5
For IIS 7.0 I used the URLScan 3.1 however this is only supported for IIS 7.0 and not 8.x
There is another solution and in my opinion this solution is the best and safe.
You can use UrlRewrite module created by the Microsoft. The Url Rewrite module redirects your url and can also change your IIS server name in the response header.
You don't have to use redirect property. You can use just change the Server header value.
Here are the steps:
First, download UrlRewrite module from this link:
http://www.iis.net/downloads/microsoft/url-rewrite and install
it on your IIS server. After that, restart IIS by this command on cmd
console
iisreset /restart
Add the following item to the your web config file under the <system.WebServer> tag. You can write anything to the Value item as server name.
Finally we changed the IIS version name on the data's header. Restart IIS again. via cmd console.
Bonus: If you want to test your website to see if it is working or not... You can use "HttpRequester" mozilla firefox plugin. for this plugin: https://addons.mozilla.org/En-us/firefox/addon/httprequester/
PS: I tested it and it worked for me on the IIS server. Not on the has been created temproray IIS server by the Visual studio.
It is possible now to remove Server header from web.config starting from IIS 10.0 :
<security>
<requestFiltering removeServerHeader ="true" />
</security>
More details on how to remove all unwanted/unnecessary headers can be found here.
Please note that this hides server header from the "application", as do all the other approaches. If you e.g. reach some default page or an error page generated by the IIS itself or ASP.NET outside your application these rules won't apply. So ideally they should be on the root level in IIS and that sill may leave some error responses to the IIS itself.
Note there is a bug in IIS 10 that makes it sometimes show the header even with the modified config prior to 2019.1C. It should be fixed by now, but IIS/Windows has to be updated.
Add the below code in Global.asax.cs:
protected void Application_PreSendRequestHeaders()
{
// Remove the default Server header
Response.Headers.Remove("Server");
// Optionally, add your own Server header
Response.AddHeader("Server", "My-App/1.0");
}
This has been tested to work under IIS 8.5 and 10.0.
Unfortunately most of the recommendations you will find online for removing the "Server" header in IIS will not work for IIS 8.0 and 8.5. I have found the only working option, and in my opinion, also the best, is to use an IIS Native-Code module.
Native-Code modules differ from the more common Managed modules, as they are written using the win32 APIs rather than ASP.NET. This means that they work for all requests (including static pages and images) rather than just requests that past though the ASP.NET pipeline. Using a Native-Code module, it is possible to remove unwanted headers at the very end of the request, meaning that you can remove headers (including the "Server" header) regardless of where they have been set.
Binaries and source code of an example Native-Code module for removing headers in IIS 7.0 to 8.5 are available in the following article.
https://www.dionach.com/en-au/blog/easily-remove-unwanted-http-headers-in-iis-7-0-to-8-5/
Just use clear tag in custom headers segment in web.config:
<system.webServer>
<httpProtocol>
<customHeaders>
<clear />
<add name="X-Custom-Name1" value="MyCustomValue1" />
<add name="X-Custom-Name2" value="MyCustomValue2" />
</customHeaders>
</httpProtocol>
</system.webServer>
For dynamic headers, You can use this code in Global.ascx:
protected void Application_PreSendRequestHeaders()
{
Response.Headers.Remove("Server");
Response.AddHeader("Sample1", "Value1");
}
This is dead simple. Just create a custom module:
public class HeaderStripModule : IHttpModule
{
public void Init(HttpApplication application)
{
application.PreSendRequestHeaders += (sender, args) => HttpContext.Current.Response.Headers.Remove("Server");
}
public void Dispose(){}
}
And then register in web.config or applicationHost.config if you want machine wide implementation.
<system.webServer>
<modules>
<add name="HeaderStripModule" type="MyNamespace.HeaderStripModule" />
</modules>
</system.webServer>
URLScan has been discontinued starting from IIS 7.5, since its functionalities are supposed to be available through "request filtering" option (feature added in IIS 7.5).
But the URLScan's 'Remove server header' option does not look like having any equivalent in "request filtering".
As said on this answer and this answer to you question, you can emptied the Server with URLRewrite instead, which remains available on IIS 8/8.5 (with some update required for having its UI in IIS administration console).
It turns out, looking at this blog, that URLScan can still be installed on IIS 8/8.5, if lack of official support is not an issue.
I have not tested myself. Here are the steps:
Install IIS 6 Metabase compatibility (if not already there)
Install Isapi Filters (if not already there)
Install URLScan (from download-able installer, not from web platform installer)
Configure URLScan through its ini file (by default in C:\Windows\System32\inetsrv\urlscan)
Maybe some iisreset or even a reboot should be done. URLScan should be visible in IIS among Isapi filters
In IIS Manager, at the server level, go to the Features view. Click on HTTP Response Headers. You can add/remove headers there. You can also manage the response headers at the site level as well.

Resources