.net core web API,static file images not loading properly? - asp.net-core-2.0

I have .net core web API PROJECT. I want to put some static images in this project.I have below code in start up file
var provider = new FileExtensionContentTypeProvider();
// Add new mappings
provider.Mappings[".myapp"] = "application/x-msdownload";
provider.Mappings[".htm3"] = "text/html";
provider.Mappings[".image"] = "image/png";
provider.Mappings[".png"] = "image/png";
// Replace an existing mapping
provider.Mappings[".rtf"] = "application/x-msdownload";
app.UseStaticFiles();
app.UseStaticFiles(new StaticFileOptions()
{
FileProvider = new PhysicalFileProvider(
Path.Combine(Directory.GetCurrentDirectory(), #"MyStaticFiles")),
RequestPath = new PathString("/StaticFiles"),
ContentTypeProvider = provider
});
when I run or deployed this web project, i have checked under it has StaticFiles folder has test.png
when I browse for test.tt/StaticFiles/test.png, or test.tt/wwwroot/StaticFiles/test.png or test.tt/wwwroot/StaticFiles/images/test.png
browser is not loading that image, it is displaying white page, where I check on network console of by F12,it is delivering response of type document and json.
My problem is image is not displaying, i have tried more images but not helpful.I am sure there is image,folder in my path.
can you tell how if I browse test.png,direct hitting path to get static file .net core WEB API images?

By default, static files go into the wwwroot in your project root. Calling app.UseStaticFiles(), causes this directory to be served at the base path of the site, i.e. /. As such, a file like wwwroot/images/test.png would be available at /images/test.png (note: without the wwwroot part).
I'm not sure what in the world you're doing with the rest of this code here, but you're essentially adding an additional served directory at [project root]/MyStaticFiles, which will then be served at /StaticFiles. As such, first, test.png would have to actually be in MyStaticFiles, not wwwroot, and then you'd access by requesting /StaticFiles/test.png.
However, there's no need for this other directory. If you simply want to add some additional media types, you can do that via:
services.Configure<StaticFileOptions>(o =>
{
var provider = new FileExtensionContentTypeProvider();
provider.Mappings.Add(".myapp", "application/x-msdownload");
// etc.
o.ContentTypeProvider = provider;
});
And then just use:
app.UseStaticFiles();
Nothing else is required.

Related

Blazor server app cannot download .msg files

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.

How to store file into inetpub\wwwroot instead of local machine folder on UWP application

I am currently developing a UWP application for my school project and one of the pages allows the user to take a picture of themselves. I created the feature by following this tutorial: CameraStarterKit
For now I am storing the pictures taken on my desktop's picture folder. But the requirement of my project is to store the pictures taken in a folder called "Photos" under inetpub\wwwroot.
I dont really understand what wwwroot or IIS is... hence, I have no idea how I should modify my codes and store them into the folder.
Here are my codes for storing on my local desktop:
private async Task TakePhotoAsync()
{
idleTimer.Stop();
idleTimer.Start();
var stream = new InMemoryRandomAccessStream();
//MediaPlayer mediaPlayer = new MediaPlayer();
//mediaPlayer.Source = MediaSource.CreateFromUri(new Uri("ms-appx:///Assets/camera-shutter-click-03.mp3"));
//mediaPlayer.Play();
Debug.WriteLine("Taking photo...");
await _mediaCapture.CapturePhotoToStreamAsync(ImageEncodingProperties.CreateJpeg(), stream);
try
{
var file = await _captureFolder.CreateFileAsync("NYPVisitPhoto.jpg", CreationCollisionOption.GenerateUniqueName);
Debug.WriteLine("Photo taken! Saving to " + file.Path);
var photoOrientation = CameraRotationHelper.ConvertSimpleOrientationToPhotoOrientation(_rotationHelper.GetCameraCaptureOrientation());
await ReencodeAndSavePhotoAsync(stream, file, photoOrientation);
Debug.WriteLine("Photo saved!");
}
catch (Exception ex)
{
// File I/O errors are reported as exceptions
Debug.WriteLine("Exception when taking a photo: " + ex.ToString());
}
}
For the storing of the files:
private static async Task ReencodeAndSavePhotoAsync(IRandomAccessStream stream, StorageFile file, PhotoOrientation photoOrientation)
{
using (var inputStream = stream)
{
var decoder = await BitmapDecoder.CreateAsync(inputStream);
using (var outputStream = await file.OpenAsync(FileAccessMode.ReadWrite))
{
var encoder = await BitmapEncoder.CreateForTranscodingAsync(outputStream, decoder);
var properties = new BitmapPropertySet { { "System.Photo.Orientation", new BitmapTypedValue(photoOrientation, PropertyType.UInt16) } };
await encoder.BitmapProperties.SetPropertiesAsync(properties);
await encoder.FlushAsync();
}
}
}
I would add an answer since there are tricky things about this requirement.
The first is the app can only access a few folders, inetpub is not one of them.
Using brokered Windows runtime component (I would suggest using FullTrustProcessLauncher, which is much simpler to develop and deploy) can enable UWP apps access folders in the same way as the traditional desktop applications do.
While this works for an ordinary folder, the inetpub folder, however, is different that it requires Administrators Privileges to write to, unless you turn UAC off.
The desktop component launched by the app does not have the adequate privileges to write to that folder, either.
So it think an alternative way would be setting up a virtual directory in IIS manager that maps to a folder in the public Pictures library, and the app saves picture to that folder.
From the website’s perspective, a virtual directory is the same as a real folder under inetpub, what differs is the access permissions.
Kennyzx is right here that you cannot access inetpub folder through your UWP application due to permissions.
But if your application fulfills following criteria then you can use Brokered Windows Component(a component within your app) to copy your file to any location in the system.
Your application is a LOB application
You are only targetting desktop devices(I assume this will be true because of your requirement)
You are using side-loading for your app installation and distribution.
If all three are Yes then use Brokered Windows Component for UWP, it's not a small thing that can be showed here on SO using an example. So give worth a try reading and implementing it.

Can't establish the URL of Bot Builder files stored in Azure App Service

I am developing a chatbot using NodeJS and BotBuilder. I have the file chatbot.jpg stored in a folder named image. This sits just beneath the root directory. I am able to display the image (using Kudu to find the URL) in a web browser as follows:
https://mysite.scm.azurewebsites.net/api/vfs/site/wwwroot/images/chatbot.jpg
If I remove the .scm element within the URL, I can no longer display the image.
Even more curiously, if I use the above URL in my bot code, the image doesn't display.
var welcomeCard = new builder.HeroCard(session)
.title("This is the new")
.subtitle('Virtual Assistant')
.images([
new builder.CardImage(session)
.url("http://mysite.scm.azurewebsites.net/api/vfs/site/wwwroot/images/chatbot.jpg")
alt("Virtual Assistant")
]);
session.send(new builder.Message(session)
.addAttachment(welcomeCard));
My question is, how do I find out the regular URL of the image stored in the Azure App Service, so that I can use it in my code?
From the public web, the URL should be https://mysite.azurewebsites.net/images/chatbot.jpg
The wwwroot folder is the root folder served by the app service.
Your code can't just the scm URL as that URL requires you to be logged in to the Azure portal; it's an admin URL.
To accomplish your goal, you need to configure your Restify server to serve static files.
Example Restify config (add to your bot code):
server.get(/\/images\/?.*/, restify.serveStatic({
directory: './images'
}));

Serving static files in ASP.NET 5 MVC 6

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.

Nancy on Owin doesn't serve static content

I'm running self hosted Nancy web application on Owin and have troubles with static content.
Let's say my application runs from this folder:
c:/myfolder/
My Views are in here:
c:/myfolder/Manager/Views/
so in my browser I can go to http://localhost:85/Manager and my page loads.
I simply can't make it to serve static content though, all my files are in /Content folder, I tried to place it both to /myfolder and /Manager folder with no luck.
Neither http://localhost:85/Manager/Content/css/styles.css nor http://localhost:85/Content/css/styles.css urls work
How do I get it to work?
Fixed the problem by adding these lines of code to Startup :
using Microsoft.Owin.FileSystems;
using Microsoft.Owin.StaticFiles;
...
var options = new FileServerOptions()
{
RequestPath = PathString.Empty,
FileSystem = new PhysicalFileSystem("/Path/here")
};
app.UseFileServer(options);

Resources