No 'Access-Control-Allow-Origin' header in Azure - c#

I have an Azure API app service.
I have added * to CORS settings within it.
I have another web app in Azure where I make calls to Azure API app.
Example : https://XXXXXX.XXXXXX.net/api/XXXXXX
The calls work when the api is working with small video files but whenever a video is more than 20mb, I always get -
No 'Access-Control-Allow-Origin' header is present on the requested resource.
Origin 'http://localhost:9000' is therefore not allowed access.
The response had HTTP status code 500
The API accepts an ID from the POST request and works with videos in a folder in Azure Media storage. This error doesn't happen when the video is under 20mb.
Any idea what the problem could be ?
I keep getting
500 - The request timed out.
The web server failed to respond within the specified time.
as Response and the CORS error on console.
The API call works and does its stuff though.
Here is the web.config looks like
<system.web>
<compilation debug="true" targetFramework="4.6.1" />
<httpRuntime targetFramework="4.6.1" maxRequestLength="5097151" executionTimeout="1800" />
<httpModules>
<add name="ApplicationInsightsWebTracking" type="Microsoft.ApplicationInsights.Web.ApplicationInsightsHttpModule, Microsoft.AI.Web" />
</httpModules>
</system.web>
<system.webServer>
<handlers>
<remove name="ExtensionlessUrlHandler-Integrated-4.0" />
<remove name="OPTIONSVerbHandler" />
<remove name="TRACEVerbHandler" />
<add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="*" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
</handlers>
<security>
<requestFiltering>
<requestLimits maxAllowedContentLength="5097151000"/>
</requestFiltering>
</security>
<validation validateIntegratedModeConfiguration="false" />
<modules>
<remove name="ApplicationInsightsWebTracking" />
<add name="ApplicationInsightsWebTracking" type="Microsoft.ApplicationInsights.Web.ApplicationInsightsHttpModule, Microsoft.AI.Web" preCondition="managedHandler" />
</modules>
<httpProtocol>
</httpProtocol>
</system.webServer>

There's no CORS header coming back because the response is HTTP 500, most probably due to the payload exceeding the maximum size allowed.
Amend your web.config with a larger value:
<configuration>
<system.webServer>
<security>
<requestFiltering>
<requestLimits maxAllowedContentLength="{value In Bytes}"/>
</requestFiltering>
</security>
</system.webServer>
</configuration>
From MSDN (emphasis mine) —
maxAllowedContentLength
Optional uint attribute.
Specifies the maximum length of content in a request, in bytes.
The default value is 30000000, which is approximately 28.6MB.

If there's no CORS header coming back and the CORS setting is set, then probably the application is crashing due to an exception, and it's too big to be deserialized. That was my issue.
Try debugging it with the azure cli.

Related

ASP.NET Core 2.2 Upgrade - IIS: limit request content length

We used to run our services on ASP.NET Core 1.1 until now. We just upgraded to ASP.NET Core 2.2, which went pretty smooth.
However, we are hosting on Azure App Service on Windows, which in turn seems to run IIS.
Now we have a custom section in the web.config to limit the max content length so when users upload files they know before actually uploading to the limit if their upload will fail:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<location path="api/0.1/files">
<system.web>
<httpRuntime maxRequestLength="409600" executionTimeout="3600"/>
</system.web>
<system.webServer>
<security>
<requestFiltering>
<requestLimits maxAllowedContentLength="419430400" />
</requestFiltering>
</security>
</system.webServer>
</location>
<location path="." inheritInChildApplications="false">
<system.webServer>
<handlers>
<add name="aspNetCore"
path="*"
verb="*"
modules="AspNetCoreModule"
resourceType="Unspecified"/>
</handlers>
<aspNetCore processPath="dotnet"
arguments=".\webapp.dll"
stdoutLogEnabled="false"
stdoutLogFile="\\?\%home%\LogFiles\stdout"
hostingModel="OutOfProcess"
forwardWindowsAuthToken="false"/>
</system.webServer>
</location>
</configuration>
Now, calling the route api/0.1/files (and of course all routes "beneath" files) will yield a 404 not found result with the following error message:
The resource you are looking for has been removed, had its name changed, or is temporarily unavailable.
The only fix to this I could find, was to globally limit the content length:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<location path="." inheritInChildApplications="false">
<system.webServer>
<handlers>
<add name="aspNetCore"
path="*"
verb="*"
modules="AspNetCoreModule"
resourceType="Unspecified"/>
</handlers>
<aspNetCore processPath="dotnet"
arguments=".\webapp.dll"
stdoutLogEnabled="false"
stdoutLogFile="\\?\%home%\LogFiles\stdout"
hostingModel="OutOfProcess"
forwardWindowsAuthToken="false"/>
<security>
<requestFiltering>
<!--400 MByte-->
<requestLimits maxAllowedContentLength="419430400" />
</requestFiltering>
</security>
</system.webServer>
</location>
</configuration>
What would be the correct way to set the limit per a specific route?
It is possible to use location to set limit for specific route.
Also, if you want to change the max request body size limit for a specific MVC action or controller, you can use the RequestSizeLimit attribute.
// GET api/values/5
[HttpGet("{id}")]
[RequestSizeLimit(40000000)]
public ActionResult<string> Get(int id)
{
return "value";
}
It sets the maximum allowed request length for this action method. You can apply this attribute at action level or controller level. This is the recommended approach to increase the limit in an ASP.NET Core MVC app.

ASP.NET Core web.config requestFiltering not overriding applicationhost.config

I'm trying to upload large files to an API controller action in my ASP.NET Core MVC 2.1 application. To that end I've been trying to figure out how to allow this through IIS Express which is how I'm running the application through Visual Studio. As suggested, this should be possible by adding a web.config file to the project root with the following contents:
<?xml version="1.0" encoding="utf-8"?>
<!-- Configuration for IIS integration -->
<configuration>
<system.webServer>
<security>
<requestFiltering>
<!-- 2 GB -->
<requestLimits maxAllowedContentLength="2147483647" />
</requestFiltering>
</security>
</system.webServer>
</configuration>
However, this doesn't have any effect as the application just returns HTTP Error 404.13 - Not Found, indicating the request is too large. It seems as if those settings are locked by the IIS so the web.config isn't overriding them. Yes, I'm also using attributes such as [DisableFormValueModelBinding] and [DisableRequestSizeLimit] on the controller action.
Instead I found that it works by adding the same configuration to the site in the applicationhost.config in the \.vs\config folder:
<location path="MySite">
<system.webServer>
<handlers>
<add name="aspNetCore" path="*" verb="*" modules="AspNetCoreModule" resourceType="Unspecified" />
</handlers>
<aspNetCore processPath="%LAUNCHER_PATH%" arguments="%LAUNCHER_ARGS%" stdoutLogEnabled="false" startupTimeLimit="3600" requestTimeout="23:00:00" />
<httpCompression>
<dynamicTypes>
<add mimeType="text/event-stream" enabled="false" />
</dynamicTypes>
</httpCompression>
<!-- Everything above this point is auto-generated -->
<security>
<requestFiltering>
<!-- 2 GB -->
<requestLimits maxAllowedContentLength="2147483647" />
</requestFiltering>
</security>
</system.webServer>
</location>
This file, however, is not tracked in GIT and it doesn't seem like a good solution to add it to GIT either.
Is there some security reason or other for why the web.config seemingly is not allowed to override the applicationhost.config? Or is there a solution that I just haven't been able to figure out?
I had a similar issue, I added a web.config with this
<configuration>
<system.webServer>
<security>
<requestFiltering>
<!-- This will handle requests up to 700MB (CD700) -->
<requestLimits maxAllowedContentLength="737280000" />
</requestFiltering>
</security>
</system.webServer>][1]][1]
</configuration>
posted too soon. The above solution worked for iis express server but did not for docker. Then I updated the entry
public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>()
.UseKestrel(options =>
{
options.Limits.MaxRequestBodySize = 100000000; //100MB
});
Then decorate controllers with [RequestSizeLimit(100_000_000)]
Those solutions solved locally and in prod for me.

Request redirect to /Account/Login?ReturnUrl=%2f since the installation on server

I'm working with asp.net core 2.1, I launch the app on my local machine without any problem and I can debug it and open it on the browser but when I deploy it to the server I get the rediction error and I can't login.
Here is my web.config file :
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<appSettings>
<add key="autoFormsAuthentication" value="false" />
<add key="enableSimpleMembership" value="false" />
</appSettings>
<location path="." inheritInChildApplications="false" allowOverride="false">
<system.webServer>
<handlers>
<add name="aspNetCore" path="*" verb="*" modules="AspNetCoreModule" resourceType="Unspecified" />
</handlers>
<aspNetCore processPath="dotnet" arguments=".\BusinessAdvisor.Inventory.dll" stdoutLogEnabled="false" stdoutLogFile=".\logs\stdout" />
</system.webServer>
<system.web>
<trust level="Full" />
</system.web>
</location>
<system.web>
<authentication mode="None" />
<compilation defaultLanguage="c#" debug="true" />
</system.web>
<connectionStrings>
<add name="DefaultConnection" connectionString="server=localhost;user id=????_dba;password=???????;database=atechdzc_mobiserv;allowuservariables=True;persistsecurityinfo=True;SslMode=none" />
</connectionStrings>
</configuration>
<!--ProjectGuid: 5d471955-9737-4896-a960-3eb7ede4494e-->
I tried all the solutions montioned but I get the same error !
EDIT :
When I make the authentification to "Windows authentication" the error doesn't appear and if I make it as "Anonymous authentication" the error still here.
It was an error on my connection string and then the migration didn't update changes automaticaly. I fixed my connection string on appsettings.production.json and I updated the database.
For me, my IIS App pool runs under a specific account. When I had to re-create the database, I had to grant permissions to that account to the database.

Web API 2 URL routing 403/404 error on IIS 7.5

I am implementing a RESTful web services host using ASP.Net 4.5 and Web Api 2 Attribute Routing. I also included Web Api Help Pages. When I run it locally through Visual Studio 2012 on IIS Express it works great and looks really cool; it displays the default /home/index page with an API menu that shows the documentation for all my RESTful API functions. I have also tested all the API methods with SOAPUI and running locally everything works perfectly.
But the URL routing absolutely refuses to work when deployed to IIS 7.5 on Windows 2008 Server R2.
When I browse the site I get:
403 - Forbidden: Access is denied.
If I try the /home/index or any of the routes of my web api methods I get:
404 - File or directory not found.
I have installed .Net 4.5 on the server and then went to Windows\Microsoft.NET\Framework64 and ran:
Aspnet_regiis -i
iisreset
I deployed my app to IIS and set the Application Pool to use .Net Framework v4.0.30319 and Managed pipeline mode: Integrated.
I have the following settings in my web.config:
<system.web>
<compilation debug="true" targetFramework="4.5" />
<httpRuntime targetFramework="4.5" />
<authentication mode="None" />
<pages>
<namespaces>
<add namespace="System.Web.Helpers" />
<add namespace="System.Web.Mvc" />
<add namespace="System.Web.Mvc.Ajax" />
<add namespace="System.Web.Mvc.Html" />
<add namespace="System.Web.Optimization" />
<add namespace="System.Web.Routing" />
<add namespace="System.Web.WebPages" />
</namespaces>
</pages>
</system.web>
<system.webServer>
<validation validateIntegratedModeConfiguration="false" />
<modules runAllManagedModulesForAllRequests="true" />
<handlers>
<remove name="ExtensionlessUrlHandler-ISAPI-4.0_32bit" />
<remove name="ExtensionlessUrlHandler-ISAPI-4.0_64bit" />
<remove name="ExtensionlessUrlHandler-Integrated-4.0" />
<add name="ExtensionlessUrlHandler-ISAPI-4.0_32bit" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework\v4.0.30319\aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv4.0,bitness32" responseBufferLimit="0" />
<add name="ExtensionlessUrlHandler-ISAPI-4.0_64bit" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework64\v4.0.30319\aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv4.0,bitness64" responseBufferLimit="0" />
<add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
</handlers>
</system.webServer>
I have tried many different variations on the web.config entries. For example, the suggestion in this post does not work either:
<modules>
<remove name="UrlRoutingModule-4.0" />
<add name="UrlRoutingModule-4.0" type="System.Web.Routing.UrlRoutingModule" preCondition="" />
<!-- any other modules you want to run in MVC e.g. FormsAuthentication, Roles etc. -->
</modules>
Nor does changing the Handlers section like this have any effect:
<handlers>
<remove name="ExtensionlessUrlHandler-Integrated-4.0" />
<remove name="OPTIONSVerbHandler" />
<remove name="TRACEVerbHandler" />
<remove name="WebDAV" />
<add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="*" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
<add name="MiniProfiler" path="mini-profiler-resources/*" verb="*" type="System.Web.Routing.UrlRoutingModule" resourceType="Unspecified" preCondition="integratedMode" />
</handlers>
I did try turning directory browsing on and then it showed the website contents just fine, so the 403 Forbidden error is because directory browsing was forbidden.
But I don't want to browse the contents, I want URL routing to work. In RouteConfig.cs file I have a default route:
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
So if URL routing were working then it should show the Home/Index view by default.
I also tried adding an Index.html file to the site and that worked fine too. So the website works fine as a website, but URL routing refuses to work.
Try to add this attribute to < modules > tag in web.config
runAllManagedModulesForAllRequests="true"

httphandler in asp.net never gets called

I have a web application running in .net framework 2.0 and hosted on IIS 7.5. The app pool is running in classic mode. I want to intercept all the requests containing .txt files. Below is my entry in web.config
<system.webServer>
<validation validateIntegratedModeConfiguration="false"/>
<handlers>
<add name="NES.HiLo.Security.CommunityResource, NES.HiLo.Security" verb="*" path="*.txt" type="NES.HiLo.Security.CommunityResource, NES.HiLo.Security" />
</handlers>
</system.webServer>
<httpHandlers>
<add verb="*" path="*.txt" type="NES.HiLo.Security.CommunityResource, NES.HiLo.Security" />
</httpHandlers>
When I m making requests for URL like
http://local.mysite.com/media/CLT/ResourceUploads/1000277/Test1.txt
the handler never kicks in, the control never comes inside the code in the handler.
Any ideas what I m missing? thanks
According to the MSDN example of registering handler in IIS 7.0 in classic mode, you are missing a couple of attributes:
<system.webServer>
<validation validateIntegratedModeConfiguration="false"/>
<handlers>
<add name="CommunityResourceHandler" verb="*" path="*.txt"
type="NES.HiLo.Security.CommunityResource, NES.HiLo.Security"
modules="IsapiModule"
scriptProcessor="FrameworkPath\aspnet_isapi.dll"
resourceType="File" />
</handlers>
</system.webServer>
<httpHandlers>
<add verb="*" path="*.txt" type="NES.HiLo.Security.CommunityResource, NES.HiLo.Security" />
</httpHandlers>

Categories