This question already has answers here:
Remove "Server" header from ASP.NET Core 2.1 application
(7 answers)
Closed 1 year ago.
I have an asp .net core web api which acts as a proxy to some other asp .net core web api services.
Everything works great, except I can't get this header to stop appearing in responses:
server: Microsoft-IIS/10.0
I added this to web.config in both proxy and service projects
<system.webServer>
<httpProtocol>
<customHeaders>
<remove name="X-Powered-By" />
<remove name="Server" />
</customHeaders>
</httpProtocol>
</system.webServer>
And it seems to work for X-Powered-By, but not Server
I also tried adding
<security>
<requestFiltering removeServerHeader="true" />
</security>
Now the header reads
server: Kestrel
Does anyone know why that would be, and how I can get this to work?
This one works on IIS 10.
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<system.webServer>
<security>
<requestFiltering removeServerHeader="true" />
</security>
</system.webServer>
</configuration>
As far as I know, if you want to remove the server header Kestrel, I suggest you could try below ways.
You could try to modify the UseKestrel setting in Program.CS:
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
webBuilder.UseKestrel(option => option.AddServerHeader = false);
});
Result:
Related
I'm getting a '405 Method Not Allowed' when I attempt for a DELETE in my staging environment.
Is there something I should be looking out for?
When I run it on my local machine (IIS 10.0) it works fine and is able to delete an ID but when I run it on my staging environment it doesn't work and returns a 405 error on swagger.
This only seems to be occurring for all delete endpoints
This is how I've implemented delete endpoints:
[HttpDelete]
[Route("{Id}")]
current output from response header:
allow: GET, HEAD, OPTIONS, TRACE
content-length: 1293
content-type: text/html
date: Mon, 14 Sep 2020 04:15:15 GMT
server: Microsoft-IIS/8.5
x-powered-by: ASP.NET
x-powered-by-plesk: PleskWin
I've got the current setup for my startup.cs
private static void ConfigureCors(IServiceCollection services)
{
services.AddCors(o => o.AddPolicy("testAppPolicy", builder =>
{
builder.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader()
.Build();
}));
}
I know it's quite a vague question but any tips on where I could start looking on how to debug this situation?
According to your description and error message, I suggest you could firstly make sure you have installed the right asp.net core module for the staging server.
Then I suggest you could try to remove the WebDAVModule in the IIS server.
More details, you could try to modify the web.config as below format.
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<system.webServer>
<modules>
<remove name="WebDAVModule" />
</modules>
<handlers>
<remove name="WebDAV" />
<!-- I removed the following handlers too, but these
can probably be ignored for most installations -->
<remove name="ExtensionlessUrlHandler-Integrated-4.0" />
<remove name="OPTIONSVerbHandler" />
<remove name="TRACEVerbHandler" />
</handlers>
<aspNetCore processPath="yourasp.net core config"
stdoutLogEnabled="false"
stdoutLogFile=".\logs\stdout" />
</system.webServer>
</configuration>
I have all aspnetcore movdulev2, all necessary software instaled on the server. IIS recognizes the web site and I put a default page that shows up. THe only probelem is when I hot the controller/action from the root application path of the webAPi app I get 404. I have tried different formats of routing, including a default .Net core 3 app from Microsoft. Everything works on my local IIS Express but not on IIS. App pool is .NttCore NoManaged Apppool. I do not have any permission issues.
My program .cs & Web.config are below:
public class Program
{
public static void Main(string[] args)
{
CreateHostBuilder(args).Build().Run();
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseContentRoot(Directory.GetCurrentDirectory());
webBuilder.UseStartup<Startup>();
});
}
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<location path="." inheritInChildApplications="false">
<system.webServer>
<handlers>
<add name="aspNetCore" path="c:\program files\dotnet\dotnet.exe" verb="*"
modules="AspNetCoreModuleV2" resourceType="Unspecified" />
</handlers>
<aspNetCore processPath="dotnet" arguments=".\WebApplication2Test.dll" stdoutLogEnabled="false"
stdoutLogFile=".\logs\stdout" hostingModel="inprocess" />
</system.webServer>
</location>
</configuration>
If anyone can help provide direction that will help.
From your frt log, the routing module responsible for asp.net did not work. The request should have entered the routing pipeline but went to the static file processing module of iis. iis looked up in the file system according to the url but did not find it, so a 404 was reported. . You can use the following configuration to force the routing module to work.
<system.webServer>
.....
<modules runAllManagedModulesForAllRequests="true" />
.....
</system.webServer>
I’m trying to remove the response Server header from an Azure Web App ( with an ASP Net core application )
After many tries of changing the web.config and removing the header in app code using a middleware, Microsoft doesn’t give up and set the response header to Server: Microsoft-IIS/10.0 :)
The problem appears only when I’m trying to access the server on http (not https). Response code from the server is 301, and this is the only response that has the Server header.
Checking the logs I was not able to find any request to http://, and perhaps this is why I’m not able to remove header, because the request is not process in my application code.
A solution that I’m thinking is to disable the azure HTTPS only and do the redirect to https in my code (I tested and is working - server header is removed)
Is there another workaround without disabling the HTTPS only option?
Here is what I tried
Startup.cs
public void Configure(IApplicationBuilder app)
{
app.Use(async (context, next) =>
{
context.Response.Headers.Add("server", string.Empty)
}
app.UseHttpsRedirection();
}
web.config
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<system.web>
<httpRuntime enableVersionHeader="false" />
<!-- Removes ASP.NET version header. -->
</system.web>
<system.webServer>
<httpProtocol>
<customHeaders>
<remove name="Server" />
<remove name="X-Powered-By" />
</customHeaders>
<redirectHeaders>
<clear />
</redirectHeaders>
</httpProtocol>
<security>
<requestFiltering removeServerHeader="true" />
<!-- Removes Server header in IIS10 or later and also in Azure Web Apps -->
</security>
<rewrite>
<outboundRules>
<rule name="Change Server Header"> <!-- if you're not removing it completely -->
<match serverVariable="RESPONSE_Server" pattern=".+" />
<action type="Rewrite" value="Unknown" />
</rule>
</outboundRules>
</rewrite>
</system.webServer>
</configuration>
UPDATE
When the URL of http:// is requested, IIS will process it, this time without code. So we can't control it by the code, we can only set it on the server, such as some scripts or tools. But on Azure, we have no way to directly operate as a physical server, so after exploration, I suggest that Front Door can be used to deal with this problem. Hiding server information through proxy should be a better way.
After my test, the server information is hidden, you can refer to this document . We can see from the picture that there is no 301 redirect request, and no server information in other requests.
PREVIOUS
You need to modify Global.asax.cs and Web.config file in your program.
In Global.asax.cs.
public class MvcApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
MvcHandler.DisableMvcResponseHeader = true;
PreSendRequestHeaders += Application_PreSendRequestHeaders;
}
protected void Application_PreSendRequestHeaders(object sender, EventArgs e)
{
//HttpContext.Current.Response.Headers.Remove("Server");
HttpContext.Current.Response.Headers.Set("Server","N/A");
}
}
And In Web.config.
<system.webServer>
<modules runAllManagedModulesForAllRequests="true" >
</modules>
<httpProtocol>
<customHeaders>
<remove name="X-Powered-By" />
</customHeaders>
</httpProtocol>
</system.webServer>
Then u can deploy your app. After the above code modification, access to the interface or static resources can see that the server information is modified, of course, it can also be deleted by Remove.
You also can handle special event by http status code.
protected void Application_PreSendRequestHeaders(object sender, EventArgs e)
{
//HttpContext.Current.Response.Headers.Remove("Server");
int StatusCode= HttpContext.Current.Response.StatusCode;
// handle like http status code 301
HttpContext.Current.Response.Headers.Set("Server","N/A");
}
I've added CORS to my .NET Core WebApi and it's works just fine when running on IIS 8.5 and 10, but whenever I run it on IIS 7.5 I get ..
Fetch API cannot load .. Response to preflight request doesn't pass
access control check: No 'Access-Control-Allow-Origin' header is
present on the requested resourse. Origin 'http://localhost:8080' is
therefore not allowed access. The response had HTTP status code 500. ..
I've tried tried switching from a specific origin to allowing any origin as well as adding this to my web.config:
<system.webServer>
...
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*" />
<add name="Access-Control-Allow-Methods" value="GET,PUT,POST,DELETE,OPTIONS" />
<add name="Access-Control-Allow-Headers" value="Content-Type" />
</customHeaders>
</httpProtocol>
</system.webServer>
Is there some extra step I need to take in order to get it running on IIS 7.5?
Startup.cs
public void Configure( IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory )
{
...
app.UseJwtBearerAuthentication( GetJwtBearerOptions() );
app.UseCors( ConfigureCors );
app.UseExceptionHandler( ConfigureExceptionHandler );
app.UseMvc();
}
private static void ConfigureCors( CorsPolicyBuilder builder )
{
builder
.AllowAnyOrigin()
//.WithOrigins( Configuration.GetSection( "Client" )["Url"] )
.AllowAnyHeader()
.AllowAnyMethod();
}
public void ConfigureServices( IServiceCollection services )
{
// Add framework services
services.AddOptions();
services.AddMemoryCache();
services.AddSingleton<IConfiguration>( Configuration );
services.AddCors(); // obsolete?
services.AddMvc( SetupMvcOptions )
.AddJsonOptions( SetupMvcJsonOptions );
services.Configure<JwtIssuerOptions>( ConfigureJwtIssuerOptions );
}
Web.config
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<!--
Configure your application settings in appsettings.json. Learn more at http://go.microsoft.com/fwlink/?LinkId=786380
-->
<system.webServer>
<handlers>
<add name="aspNetCore" path="*" verb="*" modules="AspNetCoreModule" resourceType="Unspecified" />
</handlers>
<aspNetCore processPath=".\Web.Services.exe" arguments="" stdoutLogEnabled="false" stdoutLogFile=".\logs\stdout" forwardWindowsAuthToken="false" />
</system.webServer>
</configuration>
<!--ProjectGuid: 90bd8dc9-484b-42c7-8074-e02397de9689-->
I have deployed an MVC3 and WCF web service as a single application. Both work as expected. GET and POST requests work perfectly, but the PUT and DELETE requests return 404 errors. These work fine locally. Initially it was requesting a username/password for PUT/DELETE requests.
Here is my WebServer config from my web.config file
<system.webServer>
<validation validateIntegratedModeConfiguration="false" />
<modules runAllManagedModulesForAllRequests="true">
<remove name="WebDAVModule" />
</modules>
<handlers>
<remove name="WebDAVModule" />
</handlers>
<security>
<authorization>
<remove users="*" roles="" verbs="" />
<add accessType="Allow" users="*"
verbs="GET,HEAD,POST,DEBUG,PUT,DELETE" />
</authorization>
</security>
</system.webServer>
Here are my PUT and DELETE methods:
[OperationContract]
[WebInvoke(UriTemplate = "{id}", Method = "PUT")]
public MyResource Put(MyResource updatedResource, int id)
{
MyResource existingResource = Database.GetResourceById(id);
existingResource.Name = updatedResource.Name;
Database.SaveResource(existingResource);
return existingResource;
}
[OperationContract]
[WebInvoke(UriTemplate = "{id}", Method = "DELETE")]
public MyResource Delete(int id)
{
MyResource sampleResource = Database.DeleteResourceById(id);
return sampleResource;
}
My set up:
.NET 4.0
MVC3
IIS 7.0
Note: I am on a shared hosting plan, therefore do not have direct access to IIS7.0 a so I need to make changes via the web.config file.
Enable Tracing on your service and see why you get a 404 error when you try for a PUT or DELETE action.