PBF (street map mapbox vector files) files are not allowed to be served /downloaded from IIS (2008 R8) and I need them to be.
The background
PBFs are served OK when using the react development server
//Startup.cs
if (env.IsDevelopment())
{
spa.UseReactDevelopmentServer(npmScript: "start");
}
These files will appear on the map correctly.
However when deploying the .NET Core app to IIS with
ASPNETCORE_ENVIRONMENT = production
set. These files are essentially blocked.
I have added the MIME type
I believe this is an IIS thing as like I say, on the react server in development they load fine.
Any clues as of why they still won't download?
Thanks
Basically IIS virtual directories aren’t supported in .net core. Due to the way .net core projects are served in IIS using a reverse proxy. So in the startup.cs file, do something like this:
// Configure the virtual directory
app.UseStaticFiles(new StaticFileOptions {
FileProvider = new PhysicalFileProvider(#"\\Server\Directory\.."),
RequestPath = "/NameOfDirectory",
ContentTypeProvider = provider,
OnPrepareResponse = (context) => {
if (!context.Context.User.Identity.IsAuthenticated) {
context.Context.Response.Redirect("LoginPage");
}
}
});
Related
I have a Blazor Server 6.0 app where I have links to download .msg files.
I have setup IIS to serve that mime-type trying both application/octet-stream and application/vnd.ms-outlook (and restarting IIS)
I have also tried to put in web.config the staticcontent tag like suggested here:
.msg file gives download error
And obviously in my program.cs I have app.UseStaticFiles();
I try to put the .msg in a non-blazor app and they work ok, so I think is not IIS related
So why I cannot download (or open automatically in outlook) this type of file, while other (docx, pdf, zip, etc.) are Ok ?
ASP.NET Core -- on the server side -- also needs to know about the files it has to serve. You can enable serving all unknown file types (I'd rather not include the relevant code as it is a major security risk), or you can add you own additional mappings like so:
var provider = new FileExtensionContentTypeProvider();
provider.Mappings[".msg"] = "application/vnd.ms-outlook";
// app.UseStaticFiles();
app.UseStaticFiles(new StaticFileOptions()
{
ContentTypeProvider = provider
});
More info in the official docs: https://learn.microsoft.com/en-us/aspnet/core/fundamentals/static-files?view=aspnetcore-7.0#fileextensioncontenttypeprovider
Additionally, Blazor Server registers custom options for serving static files (like .server.js, which is different from just .js). It's not directly exposed as a public API to configure, but you can look at the source here as to what the AddServerSideBlazor extension method actually does. The solution there relies on you calling UseStaticFiles without explicitly specifying the options, so that it can retrieve the StaticFilesOptions instance from DI.
Armed with this knowledge, you can override an already configured options instance as follows:
builder.Services.PostConfigure<StaticFileOptions>(o =>
{
((FileExtensionContentTypeProvider)o.ContentTypeProvider).Mappings[".msg"] = "application/vnd.ms-outlook";
});
This configures the already initialized options instance registered in the DI (after all other configurations happened on it, thus PostConfigure).
Note that if you would for whatever reason decide to use a different IContentTypeProvider, the unsafe cast above would need to be revised as well.
I'm trying to publish my ASP.NET Core application on Azure service. This works, but when I try to use the application functionality, I get the message
Your App Service app is up and running.
Moreover, in my wwwroot folder I don't have any .html files. I only have an Index.cshtml file, which is located in the Views/Home-folder in my application, all another files are .css, .js, etc.
When I run the application in Visual Studio in Debug mode, immediately opens the page in browser that was generated from Index.cshtml. But after the application is published in Azure, this does not happen.
What can I do to make Azure see Index.cshtml?
AFAIK, a default route would be added to Configure method of your Startup.cs file as follows:
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
I also created my .Net Core 2.0 MVC application to check this issue, it could work as expected on local side and my azure web app.
Moreover, in my wwwroot folder I don't have any .html files.
Views under Web Application and Web Apllication MVC would be compiled into {your-webapplication-assemblyname}.PrecompiledViews.dll, you could leverage ILSpy to check your DLLs.
For your issue, I would recommend you clear the web content in your web app via KUDU, or modify the publish settings and choose Remove additional files at destination under File Publish Options, then redeploy your application to Azure Web App to narrow this issue.
Are you finding index.cshtml in your web package? In case if you get index.cshtml in your final web package, you may need to add index.cshtml file type to the following in..
..YourAzureWebApp --> Application Settings --> Default Documents
I found out what the problem was. There are two types of applications, as presented below in the picture: Web Application and Web Apllication MVC. I worked with the second type of application. When I selected the first type and published the application, Azure immediately found the required index.html. I just had to choose Web Application.
But why does not it work with the second type of application (Web Apllication MVC)? I still do not know the answer to this question.
2 cents from my side as I just stuck for a while with this.
The problem was that yesterday I'd been playing around with deploying to Ubunut / Ngnix and today I decided to try Azure.
BUT I forgot to comment (disable) the following lines in my Startup:
//for nginx server
app.UseForwardedHeaders(new ForwardedHeadersOptions
{
ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto
});
and that costed me almost half of the day to find the issue.
I also put the routing in the following way
app.UseStatusCodePages();
app.UseAuthentication();
app.UseMvc(routes => {
routes.MapRoute(
name: "default",
template: "{controller=Pages}/{action=Index}");
});
Now looks like it works on Azure :)
I want to publish ASP.NET Core WebAPI Project with swagger on IIS. i want to run the Project on local machine with IP Address.
Configuration of My PC is:
Visual Studio 2017 Community RC
Windows 10
IIS
Please help me.
Have you tried "this one (learn.microsoft.com)"?
It helped for me. Don't forget to configure authentication and access to your site physical path for application pool identity you are going to use.
UPD (reply to comment):
In case you're using Swashbuckle.AspNetCore package you can try somethig like this in your ConfigureServices(IServiceCollection services):
// Register the Swagger generator, defining one or more Swagger documents
services.AddSwaggerGen(c =>
{
var info = new Info
{
Title = "My web API",
Version = "v1.0",
Contact = new Contact()
{
Email = "foo#gmail.com",
Name = "Denis",
Url = "https://stackoverflow.com"
},
Description = "My API"
};
c.SwaggerDoc("v1.0", info);
var basePath = AppContext.BaseDirectory; // this is not equal to wwwroot folder due to WebHostBuilder settings
var xmlPath = Path.Combine(basePath, "MyApi.xml");
c.IncludeXmlComments(xmlPath);
});
And in Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory):
// Enable middleware to serve generated Swagger as a JSON endpoint.
app.UseSwagger();
// Enable middleware to serve swagger-ui (HTML, JS, CSS etc.), specifying the Swagger JSON endpoint.
app.UseSwaggerUI(c =>
{
c.SwaggerEndpoint("/swagger/v1.0/swagger.json", "My web API v1.0");
c.EnableDeepLinking();
});
Our hosting department is not willing to allow ASP.NET core hosting with Kestrel running or even installing the ASP.NET Core Server Hosting Bundle (AspNetCoreModule).
Is there any alternative to allow ASP.NET core in this situation?
Environment: Windows Server 2012 R2 with latest IIS and .NET 4.6.2.
It is a shared hosting environment and the application(s) must be running in IIS.
You can actually run ASP.NET Core in IIS within the worker process (thus not using the ASP.NET Core Module) by using OWIN.
This is possible due to the fact that ASP.NET Core can be hosted on an OWIN server and IIS can be made an OWIN Server.
Have a look at the following OWIN middleware which shows how to run ASP.NET Core on IIS. For a more complete example, see this gist: https://gist.github.com/oliverhanappi/3720641004576c90407eb3803490d1ce.
public class AspNetCoreOwinMiddleware<TAspNetCoreStartup> : OwinMiddleware, IServer
where TAspNetCoreStartup : class
{
private readonly IWebHost _webHost;
private Func<IOwinContext, Task> _appFunc;
IFeatureCollection IServer.Features { get; } = new FeatureCollection();
public AspNetCoreOwinMiddleware(OwinMiddleware next, IAppBuilder app)
: base(next)
{
var appProperties = new AppProperties(app.Properties);
if (appProperties.OnAppDisposing != default(CancellationToken))
appProperties.OnAppDisposing.Register(Dispose);
_webHost = new WebHostBuilder()
.ConfigureServices(s => s.AddSingleton<IServer>(this))
.UseStartup<TAspNetCoreStartup>()
.Build();
_webHost.Start();
}
void IServer.Start<TContext>(IHttpApplication<TContext> application)
{
_appFunc = async owinContext =>
{
var features = new FeatureCollection(new OwinFeatureCollection(owinContext.Environment));
var context = application.CreateContext(features);
try
{
await application.ProcessRequestAsync(context);
application.DisposeContext(context, null);
}
catch (Exception ex)
{
application.DisposeContext(context, ex);
throw;
}
};
}
public override Task Invoke(IOwinContext context)
{
if (_appFunc == null)
throw new InvalidOperationException("ASP.NET Core Web Host not started.");
return _appFunc(context);
}
public void Dispose()
{
_webHost.Dispose();
}
}
Yes, you could use WebListener web server instead of Kestrel. WebListener only works on the Windows platform but since that is where you are running, it's an option for you.
WebListener however does not rely on IIS as a reverse proxy, in fact WebListener can't be used with IIS or IIS Express since it's not compatible with ASP.NET Core Module. But it does give you a non Kestrel option for hosting ASP.NET Core on windows.
You can learn more about it here: https://learn.microsoft.com/en-us/aspnet/core/fundamentals/servers/weblistener
Prior to ASP.Net Core 2.2
If you must host in IIS and you don't want to use Kestrel and you are running on windows, then there are no options. On Windows, you either host with WebListener without IIS or you host with Kestrel using IIS as a reverse proxy. Those are your only two options currently on Windows.
Update: ASP.Net Core 2.2 or later Starting in ASP.Net Core 2.2 there is now support for running ASP.Net Core In Process in IIS. Under such a configuration Kestrel is not used. To learn more see In Process Hosting Model on the Microsoft Docs site or this blog post https://weblog.west-wind.com/posts/2019/Mar/16/ASPNET-Core-Hosting-on-IIS-with-ASPNET-Core-22
My wwwroot static files aren't being resolved.
I understand that to serve static files, I need to put them in wwwroot:
favicon.ico resolves just fine, but schema/v1-0.json does not. I get the generic message:
The resource you are looking for has been removed, had its name
changed, or is temporarily unavailable.
I have the following wired up in Startup:
app.UseMiddleware<StaticFileMiddleware>(new StaticFileOptions());
app.UseStaticFiles();
I am using DNX beta6. The above require beta5 packages. I cannot find anything online regarding serving static files in beta6. I am not sure if this could be the cause of the problem.
EDIT:
As per Sirwan's answer, I have added the following, but the json file is still not available:
var options = new StaticFileOptions
{
ContentTypeProvider = new JsonContentTypeProvider(),
ServeUnknownFileTypes = true,
DefaultContentType = "application/json"
};
app.UseStaticFiles(options);
The JsonContentTypeProvider class:
public class JsonContentTypeProvider : FileExtensionContentTypeProvider
{
public JsonContentTypeProvider()
{
Mappings.Add(".json", "application/json");
}
}
I can even see the file when browsing the server:
Try this:
app.UseStaticFiles(new StaticFileOptions
{
ServeUnknownFileTypes = true,
DefaultContentType = "image/x-icon"
});
If you have multiple file types that are unknown to ASP.NET you can use FileExtensionContentTypeProvider class:
var provider = new FileExtensionContentTypeProvider();
provider.Mappings.Add(".json", "application/json");
provider.Mappings.Add(".ico", "image/x-icon");
// Serve static files.
app.UseStaticFiles(new StaticFileOptions { ContentTypeProvider = provider });
If you're using IIS, make sure you've added the correct mime-type mappings if you don't have a catch-all managed handler. Even though you don't need web.config for your website to work, IIS will still use that for your website.
Someone correct me if I'm wrong, but I believe that if you have not configured IIS to use a managed handler to serve static files it will still default to StaticFileModule and calling app.UseStaticFiles doesn't actually do anything. If you run it using dnx, however, then app.UseStaticFiles gets used.
Just a side note, you should probably also upgrade to beta7 if you haven't already.