【问题标题】:HTML does not load when refreshing the route in ASP .NET with angular使用角度刷新 ASP .NET 中的路由时不加载 HTML
【发布时间】:2021-10-06 14:20:38
【问题描述】:

我已经构建了我的 Angular 应用程序,输出是我的 ASP .NET API 文件夹中的 wwwroot 文件夹。 当我使用 dotnet watch run 构建应用程序时,一切正常并显示正常,但是当我刷新路由 localhost:5000/users 时,它显示的是原始 json 文件而不是 HTML/CSS 内容

控制台错误显示以下消息:内容安全策略:页面的设置阻止在 https://localhost:5000/favicon.ico (“default-src”) 加载资源; 在网络引用策略中说“strict-origin-when-cross-origin”,但我的 cors 设置为 app.UseCors(x=>x.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader());

我的端点

app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
               endpoints.MapFallbackToController("Index","Fallback");
            
                
            });

后备控制器

 public class FallbackController : Controller
    {
        public IActionResult Index(){

            return PhysicalFile(Path.Combine(Directory.GetCurrentDirectory(),"wwwroot","index.html"),
            "text/HTML");
        }
    }

来自 wwwroot 文件夹的 Index.html

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>SocialNetworkSPA</title>
  <base href="/">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="icon" type="image/x-icon" href="favicon.ico">
</head>
<body>
  <app-root></app-root>
</body>
</html>

我的 ASP .NET Core 版本是 3.1 和 Angular 11

错误 img

请不要在我刷新页面之前一切都正常工作,然后出现这些错误

【问题讨论】:

    标签: asp.net angular asp.net-core asp.net-web-api build


    【解决方案1】:

    试试这个:-

     app.UseCors(x => x.AllowAnyHeader().AllowAnyMethod().WithOrigins("https://localhost:xxxx"));
    

    别忘了将services.AddCors(); 添加到您的ConfigureServices。

    【讨论】:

      【解决方案2】:

      /users 路径存在路由冲突 - 它被路由到您的 API 控制器,而不是被路由到为您的 Angular 应用程序提供服务的控制器。

      您必须重新考虑您的 ASP.NET 路由配置,例如确保所有 API 路由都以 api/ 为前缀,这样就不会与 Angular 发生冲突。

      【讨论】:

        猜你喜欢
        • 2019-07-20
        • 2022-01-05
        • 1970-01-01
        • 2017-02-21
        • 1970-01-01
        • 2018-02-06
        • 2018-10-12
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多