【问题标题】:How to add css file to cshtml file?如何将css文件添加到cshtml文件中?
【发布时间】:2021-10-31 01:37:33
【问题描述】:

我一直在尝试添加一个 css 文件来设置 cshtml 文件的样式,但到目前为止我没有成功。

这是我尝试做的:

    @model mvc.Models.LoginViewModel
@{
    ViewData["Title"] = "Login";
}

<head>
    <div class="text-center">
        <h1 class="display-4">Login Page</h1>
    </div>
    <link rel="stylesheet" href="~/Content/login.css" type="text/css" />
</head>

Here is the directory tree with the two files I'm trying to link

编辑:当我将 css 样式放在 cshtml 中的“样式”标签中时,它就可以工作了。我希望有一种方法可以使用 css 文件。

你能帮帮我吗? 谢谢。

【问题讨论】:

  • 这能回答你的问题吗? How to add a .css to a .cshtml
  • 我试过了,但对我没用。
  • href="/Content/login.css"
  • ../../Content/login.css 你需要最多 2 个文件夹。现在你的链接 Views/content/login.css 你需要去 /Content/login.css
  • 我尝试上两个文件夹,还是不行。

标签: html css asp.net asp.net-core


【解决方案1】:

从你的项目结构来看,我想你可能对asp.net和asp.net core有误解。 .NET 5 是 .NET Core 的下一个版本。

你使用的是.NET 5.0,所以如果你想直接添加css引用,你需要将这些静态文件添加到根项目中的wwwroot文件夹。确保您在 Startup.cs 中添加了静态文件中间件:

app.UseStaticFiles();   //be sure add this...
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
    endpoints.MapDefaultControllerRoute();
});

然后添加如下引用:

<link rel="stylesheet" type="text/css" href="~/login.css" />

参考:Serve files in web root

如果你把静态文件放到根项目中的其他文件夹(例如Content文件夹),你需要先在Startup.cs中添加以下代码:

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    //...
    app.UseHttpsRedirection();
    app.UseStaticFiles();   // For the wwwroot folder.

    // using Microsoft.Extensions.FileProviders;
    // using System.IO;
    app.UseFileServer(new FileServerOptions
    {
        FileProvider = new PhysicalFileProvider(
            Path.Combine(env.ContentRootPath, "Content")),
        RequestPath = "/StaticFiles",
        EnableDirectoryBrowsing = true
    });

    app.UseRouting();
    app.UseAuthorization();
    app.UseEndpoints(endpoints =>
    {
        endpoints.MapControllerRoute(
        name: "default", pattern: "{controller=Home}/{action=Index}/{id?}");
    });
}

添加静态文件引用如下:

<link rel="stylesheet" type="text/css" href="/StaticFiles/login.css" />

参考:Serve files outside of web root

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-10-20
    • 1970-01-01
    • 2015-11-23
    • 2013-06-06
    • 2018-05-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多