初学笔记asp.net core

    xiaoxiao2023-10-17  162

    最近因为要做项目所以就在自学asp.net core,看的视频为B站上的杨旭出的asp.net core视频

    1.

    文件:appsettings.json

      "welcome": "Hello World"

    文件:Start.up

    var welcome = configuration[welcome];

    await context.Response.WriteAsync(welcome);

    2.

    Start.up

            public void Configure(IApplicationBuilder app, IHostingEnvironment env,IwelcomeService iwelcomeService)

            {

                if (env.IsDevelopment())

                {

                    app.UseDeveloperExceptionPage();

                }

     

                app.Run(async (context) =>

                {

                    var welcome = iwelcomeService.getMessage();

                    await context.Response.WriteAsync(welcome);

                });

            }

    生成接口

    using System;

     

    namespace WebApplication4

    {

        public interface IwelcomeService

        {

            string  getMessage();

        }

        public class WelcomeService:IwelcomeService

        {

            public string getMessage()

            {

                return "Hello from Iwelcome service";

            }

        }

    }

    发现报错

    注册接口,有3种方法

            public void ConfigureServices(IServiceCollection services)

            {

                services.AddSingleton<IwelcomeService,WelcomeService>();

            }

    services.AddSingleton<IwelcomeService,Welcome>();

    单例方法,只会生成一个实例

    Service.addtransient

    轻量级,每次都会生成一个实例

    Service.addScoped

    每次HTTP请求,都会生成一个实例

    再次运行,没有问题了

    管道和中间件

    Logger:查看所有信息,记录信息

    授权:找到特定的cookie,找不到则返回401

    路由:在web应用程序中查找响应的信息,将文件原路返回到授权和logger中,返回的是json或者是html,失败则会返回HTTP404

    添加中间件

            public void Configure(IApplicationBuilder app, IHostingEnvironment env,IwelcomeService iwelcomeService)

            {

                if (env.IsDevelopment())

                {

                    app.UseDeveloperExceptionPage();

                }

                app.UseWelcomePage();

                app.Run(async (context) =>

                {

                    var welcome = iwelcomeService.getMessage();

                    await context.Response.WriteAsync(welcome);

                });

            }

    通常用app.use……()传递参数配置中间键

                app.UseWelcomePage(new WelcomePageOptions

                {

                    Path="/welcome" 

                });

    运行

                app.Use(next =>

                {

                    return async httpContext =>

                    {

                        if (httpContext.Request.Path.StartsWithSegments("/fffff"))

                        {

                            await httpContext.Response.WriteAsync("first!!!");

                        }

                        else

                        {

                            await next(httpContext);

                        }

                    };

                });

    next表示下一个中间件

    运行截图

     

     

     

      if (env.IsDevelopment())

                {

                    app.UseDeveloperExceptionPage();

                }

    上面这段代码的意思是在开发的环境下,抛出详细信息,如果没有if的话,详细信息可能会被黑客捕获

    app.Run(async (context) =>

                {

                    throw new Exception("error");

                    var welcome = iwelcomeService.getMessage();

                    await context.Response.WriteAsync(welcome);

                });

    这样就能抛出异常的详细信息了,如果没有app.useDe……只是throw new Exception的话只会返回错误500,并不会显示详细信息

    运行截图

     

    configure函数只运行一次

    IHostingEnvironment表示生产、开发环境 env

    env.IsEnvironment("UnitTest");判断是否处于单元测试的环境

    Launch。Json文件中的

    "ASPNETCORE_ENVIRONMENT": "Development"

    ASPNETCORE_ENVIRONMENT就是环境变量属性名

    不是开发环境下处理异常

    if (env.IsDevelopment())

                {

                    app.UseDeveloperExceptionPage();

                }

                else

                    app.UseExceptionHandler();

    创建一个文件夹命名wwwroot,下面创建一个html页,命名index

    在startup中写app.UseStaticFiles();

    运行截图

    6.

    注册

            public void ConfigureServices(IServiceCollection services)

            {

                services.AddMvc();

                services.AddSingleton<IwelcomeService,WelcomeService>();

            }

    使用

                app.UseMvcWithDefaultRoute();

    创建一个类

    using System;

    using System.Collections.Generic;

    using System.Linq;

    using System.Threading.Tasks;

     

    namespace WebApplication4.Controllers

    {

        public class HomeController

        {

            public string Index()

            {

                return "Hello from HomeControllers";

            }

        }

    }

    运行截图

    MVC框架

    请求提交给Controller,Controller构建Model,Model携带客户端的信息,Controller渲染ViEW

    路由:将HTTP请求映射到正确的Controller上面

    /home/index对应的是HomeController中的index方法

               app.UseMvc(builder=>{

                    

                    builder.MapRoute("Default", "{controller}/{action}/{id?}");

                }

                    );

    运行截图

    namespace WebApplication4.Controllers

    {

     

        [Route("about")]

        public class AboutController

        {

            [Route("")]

            public string me()

            {

                return "me";

            }

        }

    }

    设置完之后运行

    Controller类

    namespace WebApplication4.Controllers

    {

        public class HomeController:Controller

        {

            public IActionResult Index()

            {

                return Content("Hello from HomeController");

            }

        }

    }

    运行截图

    与string类型一样,但是返回IActionResult是有利于单元测试的

    ObjectResult可以返回json

    返回视图

    return View();

    创建视图

    @*

        For more information on enabling MVC for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860

    *@

    @{

    }

    <!DOCTYPE html>

    <html>

    <head>

        <meta charset="utf-8" />

        <title></title>

    </head>

    <body>

        Hello from Index

    </body>

    </html>

    运行截图

    在cshtml页面中使用@符号可以写C#代码

    @model 注意m是小写表示智能提示

    @model  .....对象

    @Model表示对象

    Return View(对象名);

    最新回复(0)