413 Error: Payload Too Large - IIS - Windows Server 2016 - iis

I'm getting the http response code 413 when I try to upload a large file (>30mb) with an Asp.Net core mvc controller deployen on a windows server 2016.
The web service is running on IIS ("In process").
The controller looks like:
[Route("api/[controller]")]
[ApiController]
public class FileController : ControllerBase
{
[HttpPost]
[DisableRequestSizeLimit]
[DisableFormValueModelBinding]
public async Task<ActionResult<Guid>> Upload(IFormFile file)
{
[...]
}
}
I'm using this setting in the startup class:
public void ConfigureServices(IServiceCollection services)
{
[...]
services.Configure<FormOptions>(x =>
{
x.MultipartBodyLengthLimit = long.MaxValue;
});
}
And I have those settings in my app web.Config to prevent request size limit:
<system.webServer>
<security>
<requestFiltering>
<requestLimits maxAllowedContentLength="1073741824" />
</requestFiltering>
</security>
<serverRuntime maxRequestEntityAllowed="4294967295" uploadReadAheadSize="2147483647" />
</system.webServer>
This is working perfercly when I run it locally on my machine (windows 10 + IIS)
But as soon I publish the solution on the windows server 2016 machine I get the 413 error when I try to uplad a file >30mb.
Note: the applicationHost.Config on the server is allowing the override of the sections:
system.webServer/security/requestFiltering/requestLimits
system.webServer/serverRuntime

I realized the .net core hosting bunble version was not the same on my machine 3.1.3 than the server machine 3.1.2.
After updating it on the server with the latest available version, the upload of large files started to work without generating 413 error.

Related

Url Rewrite to another server for specific file (reverse proxy) does not work in Umbraco 8 site

I need to serve a script file from a third-party server as if it is coming from my own server. Should be a simple reverse proxy thing with url rewrite.
Prerequisites:
IIS has Url Rewrite 2.0 and ARR 3.0 installed.
What works:
when I set up an empty localhost website in IIS and add a simple rewrite rule like
<configuration>
<system.webServer>
<rewrite>
<rules>
<rule name="ReverseProxyInboundRule1" enabled="true" stopProcessing="true">
<match url="localJs/proxiedScriptFile.js" />
<action type="Rewrite" url="https://thirdpartyserver.de/js/script.js" />
</rule>
</rules>
</rewrite>
</system.webServer>
</configuration>
I can navigate to localhost/localJs/proxiedScriptFile.js and I get correctly served https://thirdpartyserver.de/js/script.js instead. So ARR and Rewrite is working.
What doesn't work:
When I add the same rewrite rule to the web.config of my existing Umbraco 8 website (on the same IIS), I get a HTTP 404.4 error, as if ARR does not work.
What I tried:
If in Umbraco 8, I change the rewrite to point to a local dummy file of
the same type, it works - the local dummy file is served. But the file off the third-party server is not.
Adding the rewrite path or url to
Umbraco.Core.ReservedUrls or Umbraco.Core.ReservedPaths does not
change the problem.
Any idea what I am facing here?
Kind regards!
Mikael
I solved my problem by using an OWIN middleware as a proxy, rather than using UrlRerwrite/ARR. This worked right away.
If someone comes up with a pure UrlRewrite/ARR solution, I am still interested. Here what works for me:
I found this ReverseProxyMiddleware for .Net Framework. Using this, my OwinStartup contains the following code:
public override void Configuration(IAppBuilder app)
{
// this must come before the base implementation so proxy kicks in before Umbraco
app.UseProxy(
new List<ProxyRule> {
// script proxy
new ProxyRule {
Matcher = uri =>
uri.AbsoluteUri.Contains("localJs/proxiedScriptFile.js")
,
Modifier = (req, user) => {
req.RequestUri = new Uri("https://thirdpartyserver.de/js/script.js");
},
RequiresAuthentication = false
}
},
r =>
{
}
);
base.Configuration(app);
}
Works like a charm. I post it here in case somebody else faces the same challenge.

ASP.NET Core 2.0 on IIS error 502.5

I install .net core 2.0 to my windows server 2008
I have two web project. Both of them work in my PC. But when I publish to my server one project work very well but other give that error
HTTP Error 502.5 - Process Failure
Application 'MACHINE/WEBROOT/APPHOST/KI-TAP.COM'
with physical root 'C:\HostingSpaces\Reseller1\ki-tap.com\wwwroot\'
failed to start process with commandline
'dotnet .\ki-tap.dll', ErrorCode = '0x80004005 : 8000808c.
I update my windows server but it still gives the same error.
here is my program.cs (I didn't add code here. This is default)
public class Program
{
public static void Main(string[] args)
{
BuildWebHost(args).Run();
}
public static IWebHost BuildWebHost(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>()
.Build();
}
and here is my web.config (published and default code )
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<system.webServer>
<handlers>
<add name="aspNetCore" path="*" verb="*" modules="AspNetCoreModule" resourceType="Unspecified" />
</handlers>
<aspNetCore processPath="dotnet" arguments=".\ki-tap.dll" stdoutLogEnabled="true" stdoutLogFile=".\logs\stdout" />
</system.webServer>
</configuration>
and here is my startup.cs(I added session configuration)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
namespace ki_tap
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
services.AddSession();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseBrowserLink();
}
else
{
app.UseExceptionHandler("/Home/Error");
}
app.UseStaticFiles();
app.UseSession();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
}
}
}
Edited:
with #set suggestion, I run that command in windows server 2008 in cmd console
C:\Program Files (x86)\dotnet\dotnet myProjectPath\project.DLL
it gives the below error. What should I do?
package: 'Microsoft.AspNetCore.Antiforgery', version: '2.0.1'
path: 'lib/netstandard2.0/Microsoft.AspNetCore.Antiforgery.dll'
his assembly was expected to be in the local runtime store as the application
s published using the following target manifest files:
aspnetcore-store-2.0.3.xml
You may have the same problem as described here in aspnet/IISIntegration repo. The solution is to add the following into .csproj file:
<PropertyGroup>
<PublishWithAspNetCoreTargetManifest>false</PublishWithAspNetCoreTargetManifest>
</PropertyGroup>
And in general, the source of this problem is that the dotnet version on your local computer and the dotnet version on the server are different.

How to setup iisnode with express?

I recently started working on nodejs. I created a simple nodejs api (with express) which connect to SQL server database and return result. After my development I had challenge how to host this node js api. I decided to host my api on IIS. I got different errors and in the end I was able to make it work. Thanks to different articles on internet.
Below are the steps I followed. May be this can help anyone who is new and trying to host nodejs in windows IIS.
I recently started working on nodejs. I created a simple nodejs api (with express) which connect to SQL server database and return result. After my development I had challenge how to host this node js api. I decided to host my api on IIS. I got different errors and in the end I was able to make it work. Thanks to different articles on internet.
Below are the steps I followed. May be this can help anyone who is new and trying to host nodejs in windows IIS.
Step 1: Install IISnode. Make sure to select correct bit version as per your machine. I was using windows 10 64 bit. I installed iisnode-full-v0.2.21-x64.msi
https://github.com/azure/iisnode/wiki/iisnode-releases
Step 2: Install URL rewrite module
https://www.iis.net/downloads/microsoft/url-rewrite
Step 3: For my use I created a new website in IIS with name "Node Web Site". This site is running on port 90. Point this web site to physical path where your Nodejs api is available.
Step 4: Provide node js api folder access to "IIS_IUSRS" group. You will get access error if don't provide access.
Step 5: Add a web.config file in your node js api folder. Add below code in your config file. This will tell IIS that server.js will be handled by IISnode.
Note: I have only one file in my project (server.js). If you have multiple files then you can add all those files here.
<configuration><system.webServer><handlers><add name="iisnode" path="server.js" verb="*" modules="iisnode" /></handlers>
</system.webServer></configuration>
Step 6: Add URL rewrite rule in your config file. This is required to make url user friendly. otherwise you need to provide .JS file path in the url. below is the final config file which I have in my application.
<configuration>
<system.webServer>
<handlers>
<add name="iisnode" path="server.js" verb="*" modules="iisnode" />
</handlers>
<rewrite>
<rules>
<rule name="api">
<match url="api/*" />
<action type="Rewrite" url="server.js" />
</rule>
</rules>
</rewrite>
<security>
<requestFiltering>
<hiddenSegments>
<add segment="node_modules" />
</hiddenSegments>
</requestFiltering>
</security>
</system.webServer>
</configuration>
Before Rewrite section I was calling my application with url http://localhost/nodesample1/server.js
After rewrite url can be like
http://localhost/nodesample1/api
Step 7: Now you need to make changes in get call of express. you need to provide full path in get call.
for example before hosting application in IISNode my default get call code was like below snippet
var express = require('express');
var bodyParser = require('body-parser');
var app = express();
app.use(bodyParser());
app.get('/', function (request, response) {
response.write('running');
response.end();
});
But after IISNode hosting I had to change my get call like below
var express = require('express');
var bodyParser = require('body-parser');
var app = express();
app.use(bodyParser());
app.get('nodesample1/api', function (request, response) {
response.write('running');
response.end();
});
As I want me url to be like "http://localhost/nodesample1/api" I had to provide complete path in get call.
That's it.
This approach worked for me.

Angular 2 in dev and production with IIS and webpack

I'm building an Angular 2 web application that communicates with webapis to get data, the app will be hosted on IIS with Windows authentication and I have some questions :
Should I use system.config as the main examples of Angular 2 work with?
If so, what about production and how can I work with sass?
Should I use webpack as angular-cli? If so, how can I combine with the advantages of the webpack Dev server (Hot reloading, sass trans-pilers, etc.)
and IIS hosting with Windows authentication?
Sorry if the questions are irrelevant but I'm a .NET developer and new to Angular 2 and Webpack.
You can use the angular-cli to develop the angular 2 app. To deploy the app on production on IIS you can use:
ng-build --prod command from angular-cli command prompt to build the app. This will generate the files required for deployment in dest folder. These are just HTML, javascript, css and other assets that your app uses.
You can copy contents of dest folder and deploy in folder of your IIS web application.
Note:
Angular 2 routing (with hash) will work without any issue on IIS. Just create default URL rewrite rule which will redirect all the requests to index.html file of your angular app. Rule will redirect all requests to index.html except for required js files and actual angular app urls (i.e. index.html or index.html#/{route-value}.
EX: <rules> <rule name="Default"> <match url="(.* ).js|index.html(.*)" negate="true" /> <action type="Rewrite" url="/index.html" /> </rule> </rules>
Angular 2 routing (without hash) will not work with IIS. In case of pure HTML application IIS will be routing the incoming request and it will redirect the request to error page if such page does not exist at that location.
In case of .Net MVC application you can create a default route to handle all the incoming request url's and redirect it to your angular index view.
Ex Route for MVC application:
routes.MapRoute(
name: "Angular",
url: "{*url}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional },
constraints: new { url = new AppFeatureUrlConstraint() }
public class AppFeatureUrlConstraint : IRouteConstraint
{
public bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection)
{
if (values[parameterName] != null)
{
var url = values[parameterName].ToString();
if (url.StartsWith("angular/", StringComparison.InvariantCultureIgnoreCase))
return true;
else
return false;
}
return false;
}
}
I recommend Angular cli with webpack. It has hot module reloading already integrated and has out of the box development and production environments with bundling and tree shaking functionality.

Remove Server: Microsoft-IIS/8.5 header from Response headers

I have IIS 8.5 installed on my Windows server 2012 R2. I am trying to remove the Server: Microsoft-IIS/8.5 header from my responses.
I tried installed URLScan but it fails to install with the following error
IIS Metabase is required to install Microsoft URLScan Filter v3.1.
I have tried to remove it from the UrlRewrite settings on my website but it's not working. Can anyone please help.
I'm using a custom module to clean my headers inside the app:
public class HeadersCleanupModule : IHttpModule
{
public void Init(HttpApplication context)
{
context.PostReleaseRequestState += application_PostReleaseRequestState;
}
void application_PostReleaseRequestState(object sender, EventArgs e)
{
HttpContext.Current.Response.Headers.Remove("Server");
HttpContext.Current.Response.Headers.Remove("X-AspNet-Version");
HttpContext.Current.Response.Headers.Remove("ETag");
}
}

Resources