0

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.

1
  • 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. Commented Jul 3, 2023 at 0:40

2 Answers 2

2

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:

enter image description here

enter image description here

Note: Please refer to the official document for more details here. In addition, sample can be found here.

Sign up to request clarification or add additional context in comments.

Comments

0

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();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.