.net core 2.0 mvc 初步学习

mvc_study

html,body,div,span,applet,object,iframe,h1,h2,h3,h4,h5,h6,p,blockquote,pre,a,abbr,acronym,address,big,cite,code,del,dfn,em,img,ins,kbd,q,s,samp,small,strike,strong,sub,sup,tt,var,b,u,i,center,dl,dt,dd,ol,ul,li,fieldset,form,label,legend,table,caption,tbody,tfoot,thead,tr,th,td,article,aside,canvas,details,embed,figure,figcaption,footer,header,hgroup,menu,nav,output,ruby,section,summary,time,mark,audio,video { margin: 0; padding: 0; border: 0 }
body { font-family: Helvetica, arial, freesans, clean, sans-serif; font-size: 14px; line-height: 1.6; color: #333; background-color: #fff; padding: 20px; max-width: 960px; margin: 0 auto }
body>*:first-child { margin-top: 0 !important }
body>*:last-child { margin-bottom: 0 !important }
p,blockquote,ul,ol,dl,table,pre { margin: 15px 0 }
h1,h2,h3,h4,h5,h6 { margin: 20px 0 10px; padding: 0; font-weight: bold }
h1 tt,h1 code,h2 tt,h2 code,h3 tt,h3 code,h4 tt,h4 code,h5 tt,h5 code,h6 tt,h6 code { font-size: inherit }
h1 { font-size: 28px; color: #000 }
h2 { font-size: 24px; border-bottom: 1px solid #ccc; color: #000 }
h3 { font-size: 18px }
h4 { font-size: 16px }
h5 { font-size: 14px }
h6 { color: #777; font-size: 14px }
body>h2:first-child,body>h1:first-child,body>h1:first-child+h2,body>h3:first-child,body>h4:first-child,body>h5:first-child,body>h6:first-child { margin-top: 0; padding-top: 0 }
a:first-child h1,a:first-child h2,a:first-child h3,a:first-child h4,a:first-child h5,a:first-child h6 { margin-top: 0; padding-top: 0 }
h1+p,h2+p,h3+p,h4+p,h5+p,h6+p { margin-top: 10px }
a { color: #4183C4; text-decoration: none }
a:hover { text-decoration: underline }
ul,ol { padding-left: 30px }
ul li>:first-child,ol li>:first-child,ul li ul:first-of-type,ol li ol:first-of-type,ul li ol:first-of-type,ol li ul:first-of-type { margin-top: 0px }
ul ul,ul ol,ol ol,ol ul { margin-bottom: 0 }
dl { padding: 0 }
dl dt { font-size: 14px; font-weight: bold; font-style: italic; padding: 0; margin: 15px 0 5px }
dl dt:first-child { padding: 0 }
dl dt>:first-child { margin-top: 0px }
dl dt>:last-child { margin-bottom: 0px }
dl dd { margin: 0 0 15px; padding: 0 15px }
dl dd>:first-child { margin-top: 0px }
dl dd>:last-child { margin-bottom: 0px }
pre,code,tt { font-size: 12px; font-family: Consolas, "Liberation Mono", Courier, monospace }
code,tt { margin: 0 0px; padding: 0px 0px; white-space: nowrap; border: 1px solid #eaeaea; background-color: #f8f8f8 }
pre>code { margin: 0; padding: 0; white-space: pre; border: none; background: transparent }
pre { background-color: #f8f8f8; border: 1px solid #ccc; font-size: 13px; line-height: 19px; overflow: auto; padding: 6px 10px }
pre code,pre tt { background-color: transparent; border: none }
kbd { background-color: #DDDDDD; background-image: linear-gradient(#F1F1F1, #DDDDDD); background-repeat: repeat-x; border-color: #DDDDDD #CCCCCC #CCCCCC #DDDDDD; border-style: solid; border-width: 1px; font-family: "Helvetica Neue", Helvetica, Arial, sans-serif; line-height: 10px; padding: 1px 4px }
blockquote { border-left: 4px solid #DDD; padding: 0 15px; color: #777 }
blockquote>:first-child { margin-top: 0px }
blockquote>:last-child { margin-bottom: 0px }
hr { clear: both; margin: 15px 0; height: 0px; overflow: hidden; border: none; background: transparent; border-bottom: 4px solid #ddd; padding: 0 }
table th { font-weight: bold }
table th,table td { border: 1px solid #ccc; padding: 6px 13px }
table tr { border-top: 1px solid #ccc; background-color: #fff }
table tr:nth-child(2n) { background-color: #f8f8f8 }
img { max-width: 100% }

StudyStartup

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Web.Study.ConfigModel;
using Web.Study.MonsterInterface;

namespace Web.Study.InhertStartup
{
    public class StudyStartup
    {

        protected IConfiguration Configuration { get; set; }

        public StudyStartup()
        {

        }

        /// <summary>
        /// 用于获取配置信息
        /// </summary>
        /// <param name="configuration"></param>
        public StudyStartup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IServiceProvider ConfigureServices(IServiceCollection services)
        {

            //注入mvc
            services.AddMvc();

            //添加Options
            services.AddOptions();

            //获取配置信息
            services.Configure<AppSetting>(Configuration.GetSection(nameof(AppSetting)));

            //开启Session功能
            services.AddSession(options ={
                options.IdleTimeout = TimeSpan.FromMinutes(30);
            });

            //构建一个默认的serviceProvider处理对象
            return services.BuildServiceProvider();
        }

        public void Configure(IApplicationBuilder app,
            IHostingEnvironment environment,
            ILoggerFactory loggerFactory,
            IHttpContextFactory httpContextFactory,
            DiagnosticSource diagnosticSource,
            DiagnosticListener diagnosticListener)
        {
            //当前环境为开发环境
            if (environment.IsDevelopment())
            {
                app.UseBrowserLink();
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
            }

            // 重要: session的注册必须在UseMvc之前,因为MVC里面要用
            app.UseSession();

            //使用webroot中的静态文件
            app.UseStaticFiles();

            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");
            });
        }
    }
}

Program

    public static IWebHost BuildWebHost<T>(string[] args) where T:class
    {
        IWebHostBuilder webHostBuilder = WebHost.CreateDefaultBuilder(args);

        IWebHostBuilder hostBuilder = webHostBuilder.UseStartup<T>();

        IWebHost webHost = hostBuilder.Build();

        return webHost;

    }

code explain

construction

public StudyStartup(IConfiguration configuration)

相关源码
IWebHostBuilder webHostBuilder = WebHost.CreateDefaultBuilder(args);

方法解析

public static IWebHostBuilder CreateDefaultBuilder(string[] args)
{
  return new WebHostBuilder()
      .UseKestrel()//Specify Kestrel as the server to be used by the web host.
      .UseContentRoot(Directory.GetCurrentDirectory())//采用当前目录作为内容跟目录
      //配置信息处理
      .ConfigureAppConfiguration((Action<WebHostBuilderContext, IConfigurationBuilder>) ((hostingContext, config) =>
      {
             //注入运行环境
            IHostingEnvironment hostingEnvironment = hostingContext.HostingEnvironment;
              //加载配置文件
            config.AddJsonFile("appsettings.json", true, true).AddJsonFile(string.Format("appsettings.{0}.json", (object) hostingEnvironment.EnvironmentName), true, true);
          //根据运行环境加载相应文件
            if (hostingEnvironment.IsDevelopment())
            {
              Assembly assembly = Assembly.Load(new AssemblyName(hostingEnvironment.ApplicationName));
              if (assembly != (Assembly) null)
                config.AddUserSecrets(assembly, true);
            }

            config.AddEnvironmentVariables();
            if (args == null)
              return;
            config.AddCommandLine(args);
      }))
      //配置日志信息
      .ConfigureLogging((Action<WebHostBuilderContext, ILoggingBuilder>) ((hostingContext, logging) =>
      {
        logging.AddConfiguration((IConfiguration) hostingContext.Configuration.GetSection("Logging"));
        logging.AddConsole();
        logging.AddDebug();
      }))
      .UseIISIntegration()//采用IIS进行发布
      .UseDefaultServiceProvider((Action<WebHostBuilderContext, ServiceProviderOptions>) ((context, options) => options.ValidateScopes = context.HostingEnvironment.IsDevelopment()));//采用默认的处理机制
}

即若需要使用startup的有参构造,则需要在configureappconfiguration中进行配置相应处理类

请求走向:

初始:Run --> ConfigureServices --> Configure

配置信息的获取:

<Controller>

protected AppSetting ConfigInfo { get; set; }

    //读取配置信息
protected BaseController(IOptions<AppSetting> options) => ConfigInfo = options.Value;

DI注入

1.创建的DI注入在ConfigureServices进行处理

注入方式:

services.AddSingleton(u => new MonsterDIController(new GuestDal()));//指定控制器进行注入

services.AddSingleton<IDal,DefaultDal>();//统一注入  全局共享一个

services.AddTransient<IDal, DefaultDal>();//统一注入    每次使用都不一样,不同的类或不同的方法使用都不一样

services.AddScoped<IDal, EmptyDal>();//统一注入   一次请求共享一个对象

注:
    当对同一类型构造传入不同类型对象的注入时,
    不考虑注入类型或范围
    已最终注入类型为传入对象创建实例

例如:
    <Controller>

        protected IDal Dal { get; set; }

        public MonsterDIController(IDal dal)
        {
            this.Dal = dal;
        }

    <ConfigureServices>
        如上述一致

    <Result>
        最终创建实例时,会传入EmptyDal

开启Session功能:

<method --> ConfigureServices>

    services.AddSession(options => {
            options.IdleTimeout = TimeSpan.FromMinutes(30);//存储时长
        });

<method --> Configure >
    // 重要: session的注册必须在UseMvc之前,因为MVC里面要用
        app.UseSession();

原文地址:https://www.cnblogs.com/monster17/p/9125165.html

时间: 2024-10-27 12:15:57

.net core 2.0 mvc 初步学习的相关文章

ASP.NET Core 2.0 MVC项目实战

 一.前言 毕业后入职现在的公司快有一个月了,公司主要的产品用的是C/S架构,再加上自己现在还在学习维护很老的delphi项目,还是有很多不情愿的.之前实习时主要是做.NET的B/S架构的项目,主要还是用的那种传统的开发模式,只有一个项目用到了Web API,自己负责后端的接口功能实现.既然现在没办法改变现状,那就先改变自己吧.定了个计划,下班后慢慢的开始学习ASP.NET Core Web API和Vue,准备从前端到后端自己写一个小项目玩玩,毕竟代码这个东西,时间长了是会忘的.       

ASP.NET CORE 1.0 MVC API 文档用 SWASHBUCKLE SWAGGER实现

from:https://damienbod.com/2015/12/13/asp-net-5-mvc-6-api-documentation-using-swagger/ 代码生成工具: https://github.com/NSwag/NSwag This article shows how to document your ASP.NET Core 1.0 MVC API using Swagger with Swashbuckle. Per default, it does not us

.net core 2.0 mvc 获取配置信息

mvc_core_config html,body,div,span,applet,object,iframe,h1,h2,h3,h4,h5,h6,p,blockquote,pre,a,abbr,acronym,address,big,cite,code,del,dfn,em,img,ins,kbd,q,s,samp,small,strike,strong,sub,sup,tt,var,b,u,i,center,dl,dt,dd,ol,ul,li,fieldset,form,label,lege

使用VS Code开发.Net Core 2.0 MVC Web应用程序教程之一

好吧,现在我们假设你已经安装好了VS Code开发工具..Net Core 2.0预览版的SDK dotnet-sdk-2.0.0(注意自己的操作系统),并且已经为VS Code安装好了C#扩展(在VS Code的扩展菜单中输入OmniSharp,安装扩展即可) 一.我们先在我们的电脑硬盘的某个神奇的目录下新建一个文件夹.我把这个地方选在D:\WorkTest下,创建的文件夹名称为MyCMS.注意,这一步不是在VS Code中完成的,貌似VS Code中不能创建文件夹. 二.在VS Code开发

VSCODE Net Core 2.0 MVC

1.目录结构 2.运行此命令还原新建MVC文件结构 dotnet new sln -n 项目文件名称不带后缀名 cd Web文件夹名称 dotnet new mvc 生成对应的dll文件 3.配置launch.json 1 { 2 // 使用 IntelliSense 了解相关属性. 3 // 悬停以查看现有属性的描述. 4 // 欲了解更多信息,请访问: https://go.microsoft.com/fwlink/?linkid=830387 5 "version": "

mazing ASP.NET Core 2.0【转】

前言 ASP.NET Core 的变化和发展速度是飞快的,当你发现你还没有掌握 ASP.NET Core 1.0 的时候, 2.0 已经快要发布了,目前 2.0 处于 Preview 1 版本,意味着功能已经基本确定,还没有学习过 ASP.NET Core 的同学可以直接从 2.0 开始学起,但是如果你已经掌握了 1.0 的话,那么你只需要了解在 2.0 中增加和修改的一些功能即可. 每一次大版本的发布和升级,总会带给开发人员一些惊喜和令人兴奋的特性,有关 ASP.NET Core 本次的 2.

NET Core 2.0 使用支付宝

ASP.NET Core 2.0 使用支付宝PC网站支付 前言 最近在使用ASP.NET Core来进行开发,刚好有个接入支付宝支付的需求,百度了一下没找到相关的资料,看了官方的SDK以及Demo都还是.NET Framework的,所以就先根据官方SDK的源码,用.NET Standard 2.0 实现了支付宝服务端SDK,Alipay.AopSdk.Core(github:https://github.com/stulzq/Alipay.AopSdk.Core) ,支持.NET CORE 2

Asp.net core 2.0.1 Razor 的使用学习笔记(一)

环境:vs2017 版本:15.5.6 这里说明下, Razor页面模式跟mvc出现了严重的不同.正如微软官方说的一样“Razor 页面是 ASP.NET Core MVC 的一个新功能,它可以使基于页面的编码方式更简单高效.” 但就代码说没有什么不同几乎完全一样,但是存放的位置却有了根本的区别.个人研究分析的结果是:Razor页面模式其实是把mvc中的控制器化整为零了,即原来控制器中的操作代码被分布放到了各个页面的.cshtml.cs文件中了.这样一来由原来mvc中文件按类型分类变成了按功能分

Professional C# 6 and .NET Core 1.0 - Chapter 41 ASP.NET MVC

What's In This Chapter? Features of ASP.NET MVC 6 Routing Creating Controllers Creating Views Validating User Inputs Using Filters Working with HTML and Tag Helpers Creating Data-Driven Web Applications Implementing Authentication and Authorization W