Home > database >  How to return a file path as a URL under the wwwroot directory using .NET 6 minimal API?
How to return a file path as a URL under the wwwroot directory using .NET 6 minimal API?

Time:01-14

Using .net 6 minimal API, what' the best way to programmatically get the wwwroot URL? So that I can transform a path like: wwwroot/audio/recording1.mp3 into a string like http://localhost:5000/audio/recording1.mp3 then return as json so that a user can access?

Something like:

var wwwrootURL = Environment.wwwrootURL;
var mp3URL  = $"{wwwrootURL}/audio/recording1.mp3"),

My code:

API in Program.cs

app.MapGet("/SearchSynonyms", SearchSynonyms);
IResult SearchSynonyms()
{
    var service = new WordService();
    var result = service.SearchSynonyms();
    return Results.Json(result);

}


WordService.cs (Returns a list of SynonymWOrds)


public record SynonymWord(string Term, string Sentence, string RecordingURL);

   public List<SynonymWord> SearchSynonyms()
        {
            
            List<SynonymWord> synonyms = new List<SynonymWord>
            {
                new SynonymWord("Detwi", "Tanpèt la pase, li detwi mezi kay nan katye a", "wwwroot/audio/detwi.ogg"),
               
                new SynonymWord("Depatcha", "Ti gason a telman dezòd, li depatcha radyo a. ", "~/audio/depatchya.ogg"),
                new SynonymWord("Demachwele", "Yo pase li yon kalòt, yo manke demachwele li", "~/audio/deplimen.ogg"),
            };
      
                return synonyms
        }

Expected result:

 {
    "term": "Deplimen",
    "sentence": "Anvan ou kwit poul la, fòk ou deplimen li",
    "recordingURL": "http://localhost:5000/audio/deplimen.mp3"
  },
  {
    "term": "Dechalbore",
    "sentence": "Ti pyebwa koumanse grandi epi kabrit la finn dechalbore li",
    "recordingURL": "http://localhost:5000/audiodechalbore.mp3"
  }

Thanks

CodePudding user response:

You can try building the url yourself from HttpContext.Request:

app.MapGet("/getpath", (HttpContext context) =>
{
    var host = context.Request.Host.ToUriComponent();

    var filePath = "PathToSomeFileInStaticFileFolder.ext";
    var url =  $"{context.Request.Scheme}://{host}/{filePath}";
    return url;
});

In case of your filenames you will need to handle replacements from wwwroot/~ to the build url (i.e. {context.Request.Scheme}://{host} part).

  •  Tags:  
  • Related