Learn extra at:
- Launch the Visible Studio 2022 IDE.
- Click on on “Create new challenge.”
- Within the “Create new challenge” window, choose “ASP.NET Core Internet API” from the listing of templates displayed.
- Click on Subsequent.
- Within the “Configure your new challenge” window, specify the identify and placement for the brand new challenge. Optionally examine the “Place resolution and challenge in the identical listing” examine field, relying in your preferences.
- Click on Subsequent.
- Within the “Extra Info” window proven subsequent, choose “.NET 9.0 (Normal Time period Assist)” because the framework model and uncheck the examine field that claims “Use controllers,” as we’ll be utilizing minimal APIs on this challenge.
- Elsewhere within the “Extra Info” window, go away the “Authentication Sort” set to “None” (the default) and ensure the examine bins “Allow Open API Assist,” “Configure for HTTPS,” and “Allow Docker” stay unchecked. We gained’t be utilizing any of these options right here.
- Click on Create.
We’ll use this ASP.NET Core Internet API challenge to work with the code examples given within the sections under.
IFormFile and IFormFileCollection in ASP.NET Core
Within the latest variations of ASP.NET Core, minimal APIs present help for importing recordsdata utilizing the IFormFile
and IFormFileCollection
interfaces. Whereas IFormFile
is used to add a single file, IFormFileCollection
is used to add a number of recordsdata. The next code snippet illustrates how one can add a single file utilizing IFormFile
in your minimal API utility.
app.MapPost("/add", async (IFormFile file) =>
{
var tempFile = Path.GetTempFileName();
utilizing var fileStream = File.OpenWrite(tempFile);
await file.CopyToAsync(fileStream);
});
Notice that the File.OpenWrite
methodology accepts the trail to a file in your file system as a parameter and returns a FileStream
occasion. As its identify signifies, a FileStream
object supplies a Stream
for a file, which means a sequence of bytes.
Equally, the next piece of code reveals how one can add a number of recordsdata utilizing the IFormFileCollection
interface.
app.MapPost("/upload_multiple_files", async (IFormFileCollection recordsdata) =>
{
foreach (var file in recordsdata)
{
var tempFile = Path.GetTempFileName();
utilizing var fileStream = File.OpenWrite(tempFile);
await file.CopyToAsync(fileStream);
}
});
Typically we’ll need to do extra with a file than merely add it. If we need to parse or manipulate the contents of a file [OK?], we will benefit from the StreamReader
class. StreamReader
is a high-level class, constructed on high of FileStream
, that permits us to learn the characters from a byte stream. StreamReader
may also deal with character encoding (UTF-8, ASCII, and many others.) if wanted.
Let’s say you will have a file that comprises creator data that you just need to insert right into a database desk. Assuming every line of textual content within the file represents a distinct creator report, you may embrace the next code in your Program.cs file to add the contents of the file, line by line, to a minimal API endpoint.
app.MapPost("/creator/add", (IFormFile file,
[FromServices] IAuthorRepository authorRepository) =>
{
utilizing var streamReader = new StreamReader(file.OpenReadStream());
whereas (streamReader.Peek() >= 0)
authorRepository.Create(streamReader.ReadLine() ?? string.Empty);
});
You would possibly use the previous code snippet to learn a group of creator knowledge represented as JSON, for instance, after which insert these data in a database desk. Notice that I’ve omitted the supply code of the IAuthorRepository
interface and its carried out courses right here for brevity.
Avoiding anti-forgery errors when importing recordsdata
When importing recordsdata in ASP.NET Core, you might usually encounter anti-forgery errors. ASP.NET Core points these errors to warn of cross-site request forgery attacks.
Determine 1: ASP.NET Core could generate an anti-forgery error when importing a file.
Foundry
In case your endpoint is protected and it doesn’t require anti-forgery safety, you’ll be able to disable anti-forgery validation for the endpoint by utilizing the DisableAntiforgery
methodology, as proven within the following code.