posts - 609,  comments - 13,  views - 64万
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

视频教程:https://www.bilibili.com/video/BV1zt411e7oc?p=1
日志功能:https://blog.csdn.net/weixin_43847283/article/details/125700821
1.IConfiguration configuration读取配置顺序:命令行启动参数》计算机系统变量》项目配置文件appsettings.Development.json(开发环境)》appsettings.json

2.注册服务
public void ConfigureServices(IServiceCollection services)
{
services.Configure<CookiePolicyOptions>(options =>
{
// This lambda determines whether user consent for non-essential cookies is needed for a given request.
options.CheckConsentNeeded = context => true;
options.MinimumSameSitePolicy = SameSiteMode.None;
});
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
//services.AddSingleton<ITestService,TestService>();//单例模式 注册服务 只存在一个实例
//services.AddTransient<ITestService, TestService>();//临时模式 每次请求都创建一个新的实例
//services.AddScoped<ITestService, TestService>();//每次Http请求,只生成一个实例
}
3.环境变量判断是否是开发环境:项目目录》Properties》launchSettings.json》ASPNETCORE_ENVIRONMENT可以修改,或者项目右键》属性》调试 可以配置。
4.访问静态文件 app.UseStaticFiles();//访问wwwroot下的文件
//访问磁盘文件
app.UseStaticFiles(new StaticFileOptions
{
FileProvider = new PhysicalFileProvider("D:/MyStaticFiles"),
RequestPath = "/StaticFiles"
});
示例:<img src="~/StaticFiles/images/banner1.svg" alt="pic"/>

app.UseStaticFiles(new StaticFileOptions
{
RequestPath = "/node_modules",
FileProvider = new PhysicalFileProvider(Path.Combine(env.ContentRootPath, "node_modules"))
});

app.UseDefaultFiles();
app.UseStaticFiles();
//app.UseFileServer();//一个等于前两个集合
5.ViewComponent:在根目录创建ViewComponents文件夹,在这里创建ViewComponent

复制代码
using Microsoft.AspNetCore.Mvc;
namespace NetCoreTestMVC2.ViewComponents
{
    public class WelcomStuViewComponent : ViewComponent
    {
        private readonly IRepository<Student> _repository;
        public WelcomStuViewComponent(IRepository<Student> repository)
        {
            this._repository = repository;
        }
        public IViewComponentResult Invoke(string text)
        {
            var count = text + "/" + _repository.Count().ToString();
            return View("Default", count);
        }
    }
}
复制代码

创建/Views/Shared/Components/WelcomStu/Default.cshtml,视图代码自己随便写:
@model string
学生总数:@Model
使用ViewComponent:

@await Component.InvokeAsync("WelcomStu", "测试")
TagHelper方式,需要在_ViewImports.cshtml加配置你项目的命名空间:@addTagHelper *, NetCoreTestMVC2
<vc:welcom-stu text="test"></vc:welcom-stu>
text就是传的参数
6.连数据库:创建数据访问类

复制代码
using Microsoft.EntityFrameworkCore;

namespace NetCoreTestMVC2
{
    public class DataContext : DbContext
    {
        public DataContext(DbContextOptions<DataContext> options) : base(options) { }
        public DbSet<Student> Students { get; set; }
    }
}
复制代码

配置数据库连接字符串:

复制代码
{
  "Logging": {
    "LogLevel": {
      "Default": "Warning"
    }
  },
  "AllowedHosts": "*",
  "ConnectionStrings": {
    "DefaultConnection": "Data Source=.;Initial Catalog=netcoretestdb;Persist Security Info=True;User ID=sa;Password=111111;"
  }
}
复制代码

注册服务:

services.AddDbContext<DataContext>(options =>
            {
                options.UseSqlServer(Configuration["ConnectionStrings:DefaultConnection"]);
            });

services.AddScoped<IRepository<Student>, StudentService>();

使用:

复制代码
public interface IRepository<T>
    {
        List<T> GetAll();
        int Count();
    }
public class StudentService : IRepository<Student>
    {
        private readonly DataContext db;

        public StudentService(DataContext context)
        {
            db = context;
        }

        public int Count()
        {
            return db.Students.Count();
        }

        public List<Student> GetAll()
        {
            return db.Students.ToList();
        }

    }
复制代码

xxx

posted on   邢帅杰  阅读(416)  评论(0编辑  收藏  举报
编辑推荐:
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
阅读排行:
· 地球OL攻略 —— 某应届生求职总结
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 提示词工程——AI应用必不可少的技术
· .NET周刊【3月第1期 2025-03-02】
点击右上角即可分享
微信分享提示