【问题标题】:Serving static content without a file extension on a Blazor server project在 Blazor 服务器项目上提供没有文件扩展名的静态内容
【发布时间】:2020-04-26 17:02:45
【问题描述】:

根据 Apple 对 Universal Links 的要求,我有一个名为“apple-app-site-association”的文件,该文件位于 azure 网站的根文件夹中。访问 mysite.com/apple-app-site-association 应该会在浏览器中返回 JSON 文本。我在 Azure 上托管该站点,并且正在运行 Blazor 服务器项目。我的项目没有 web.config 文件。

需要明确的是,文件“apple-app-site-association”不应具有“.json”的扩展名

我看过this solutionthis solution

我还尝试修改 Startup.cs 中的 Configure() 方法以提供静态文件

app.UseStaticFiles(new StaticFileOptions
{
    ServeUnknownFileTypes = true,
    DefaultContentType = "application/json"
});

虽然上面的代码确实正确地服务于 mysite.com/apple-app-site-association,但它具有 404'ing _framework/blazor.server.js 的不良副作用。

如何修改 apple-app-site-association 的 MIME 类型,以便我的 Blazor 服务器项目在访问 mysite.com/apple-app-site-association 时提供文件?

或者,使用上面的 UseStaticFiles() 方法,如何解决加载 _framework/blazor.server.js 时出现的 404 错误?

在_Host.cshtml中

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <base href="~/" />
    <link rel="stylesheet" href="css/bootstrap/bootstrap.min.css" />
    <link href="css/site.css" rel="stylesheet" />
    <link rel="stylesheet" href="_content/Radzen.Blazor/css/default.css" />
</head>
<body>
    ...some stuff...

    <script src="_framework/blazor.server.js"></script>
</body>
</html>

【问题讨论】:

    标签: azure-web-app-service mime-types blazor blazor-server-side ios-universal-links


    【解决方案1】:

    尽管您使用的是 Blazor,但它本质上仍然是一个 ASP.NET Core 应用程序,问题实际上是关于 ASP.NET Core、路由以及如何处理静态文件的问题。

    正如this answer 中所见,通过控制器执行此操作可能是最简单的,而不是试图强制路由器处理没有扩展名的 URL。我还在一个项目中为robots.txt 执行此操作,以控制不同品牌的显示内容。

    我试过这个:

        public class StaticContentController : Controller
        {
            [HttpGet]
            [Route("apple-app-site-association")]
            public ContentResult AppleAppSiteAssociation()
            {
                // source in root of wwwroot folder
                const string source = @"apple-app-site-association.json";
                string json = System.IO.File.ReadAllText(source);
                return Content(json, "application/json", Encoding.UTF8);
            }
        }
    

    源文件(带有 .json 扩展名)在项目中设置了“如果更新则复制”属性,因此它存在于 /bin 文件夹中。

    运行:

    【讨论】: