i have a minimal api application and i would like to return a path to file, most of the answers i found are for controller based APIs that use the Request to get the url from.
-
Where do you want to extract the base URL? In separate middleware or within your minimal itself? In addition, please share your current code snippet in order to get better clarity.Md Farid Uddin Kiron– Md Farid Uddin Kiron2023-07-03 00:40:55 +00:00Commented Jul 3, 2023 at 0:40
2 Answers
How can i get base url of a c# minimal api application?
In order to get, base url within minimal api you should extract the httpContext within your API and it has the property called Request.Host and Request.Path which will return you application base URL.
Base URL In Minimal API:
Let's have a look how we can extract that in practice:
app.MapGet("/baseurl", (HttpContext context) =>
{
var baseURL = context.Request.Host;
var basepath = context.Request.Path;
return Results.Ok($"Base URL: {baseURL} and base path: {basepath} thus, full path: {baseURL + basepath}");
});
Output:
Note: Please refer to the official document for more details here. In addition, sample can be found here.
Comments
If you're working with a minimal API application and you want to return a path to a file, you can use the HttpContext class available in ASP.NET Core.
Here's an example:
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Hosting;
var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();
app.MapGet("/file", async context =>
{
// Specify the path to the file
string filePath = "/path/to/file.txt";
// Set the content type based on the file extension
context.Response.ContentType = "text/plain";
// Write the file content to the response
await context.Response.SendFileAsync(filePath);
});
app.Run();

