如何使用 .NET 6 minimal API return wwwroot 目录下的 URL 文件路径?

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

使用 .net 6 minimal API,以编程方式获取 wwwroot URL 的最佳方法是什么? 这样我就可以将 wwwroot/audio/recording1.mp3 之类的路径转换为 ​​http://localhost:5000/audio/recording1.mp3 之类的字符串,然后将 return 转换为 json 以便用户可以访问?

类似于:

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

我的代码:

API 在 Program.cs

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

}


WordService.cs(Returns 同义词列表)


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
        }

预期结果:

 {
    "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"
  }

谢谢

您可以尝试通过 HttpContext.Request 自己构建 url:

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

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

对于您的文件名,您需要处理从 wwwroot/~ 到构建 url(即 {context.Request.Scheme}://{host} 部分)的替换。