No 'Access-Control-Allow-Origin' header when running ASP.NET Core WebApi on IIS 7.5, but working correctly on IIS 8.5 and 10 - asp.net-core

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-->

Related

How to remove "Server" from response headers [duplicate]

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:

“405 method not allowed” for “DELETE” method

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>

.NET Core3.0 ASP.NET Web AP gets 404 on controller actionsonly when deployed to IIS

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>

Running ServiceStack side by side with MVC

I managed to run ServiceStack side by side with MVC4, but I still have a little problem and hope someone can help me with that.
When executing a debugging session through VS2012, everthying works perfect - the browser is opened and the first page is loaded well. But then when refreshing the page, and trying to get to http://localhost:62322/Content/site.css, the following error is displayed:
Handler for Request not found:
Request.ApplicationPath: /
Request.CurrentExecutionFilePath: /Content/site.css
Request.FilePath: /Content/site.css
Request.HttpMethod: GET
Request.MapPath('~'): D:\All\Projects\ExampleProject\trunk\ExampleProject\ExampleProject\
Request.Path: /Content/site.css
Request.PathInfo:
Request.ResolvedPathInfo: /Content/site.css
Request.PhysicalPath: D:\All\Projects\ExampleProject\trunk\ExampleProject\ExampleProject\Content\site.css
Request.PhysicalApplicationPath: D:\All\Projects\ExampleProject\trunk\ExampleProject\ExampleProject\
Request.QueryString:
Request.RawUrl: /Content/site.css
Request.Url.AbsoluteUri: http://localhost:62322/Content/site.css
Request.Url.AbsolutePath: /Content/site.css
Request.Url.Fragment:
Request.Url.Host: localhost
Request.Url.LocalPath: /Content/site.css
Request.Url.Port: 62322
Request.Url.Query:
Request.Url.Scheme: http
Request.Url.Segments: System.String[]
App.IsIntegratedPipeline: False
App.WebHostPhysicalPath: D:\All\Projects\ExampleProject\trunk\ExampleProject\ExampleProject
App.DefaultHandler: DefaultHttpHandler
App.DebugLastHandlerArgs: GET|/Content/site.css|D:\All\Projects\ExampleProject\trunk\ExampleProject\ExampleProject\Content\site.css
But if I delete the following line of code in AppHost.cs, everything works well, and the handler for site.css is always found:
SetConfig(new EndpointHostConfig { ServiceStackHandlerFactoryPath = "api", DefaultContentType = ContentType.Json });
My requirements for the project are wrapping with ServiceStack any call through the browser (all controllers) as well as calls to /api, which should be handled by a ServiceStack service.
I followed the instructions here:
https://github.com/ServiceStack/ServiceStack/wiki/Run-servicestack-side-by-side-with-another-web-framework
and my web.config looks like this:
<system.web>
<!--...-->
<httpHandlers>
<add path="*" type="ServiceStack.WebHost.Endpoints.ServiceStackHttpHandlerFactory, ServiceStack" verb="*" />
</httpHandlers>
<!--...-->
</system.web>
<location path="api">
<system.web>
<httpHandlers>
<add path="*" type="ServiceStack.WebHost.Endpoints.ServiceStackHttpHandlerFactory, ServiceStack" verb="*" />
</httpHandlers>
</system.web>
<!-- Required for IIS 7.0 -->
<system.webServer>
<modules runAllManagedModulesForAllRequests="true" />
<validation validateIntegratedModeConfiguration="false" />
<handlers>
<add path="*" name="ServiceStack.Factory" type="ServiceStack.WebHost.Endpoints.ServiceStackHttpHandlerFactory, ServiceStack" verb="*" preCondition="integratedMode" resourceType="Unspecified" allowPathInfo="true" />
</handlers>
</system.webServer>
</location>
Does anybody know why the handler for site.css sometimes found and sometimes not?
Furthermore, if I did a mistake with configuring ServiceStack to wrap my whole server, please point me to them.
From what you are trying to do I would recommend starting with a plain ASP.NET Web Application. Once your project is set, using NuGet you could do
Install-Package ServiceStack.Host.AspNet
or just follow the configuration here. Doing this runs ServiceStack at the root path /.
In your set up above you don't need this line...
SetConfig(new EndpointHostConfig { ServiceStackHandlerFactoryPath = "api", DefaultContentType = ContentType.Json });
Adding it is telling ServiceStack to only handle requests that contain the '/api' path which is not what you want.

404 errors for PUT and DELETE requests on deployed WCF RESTful Service

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.