Startup里面的一些用法

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Configuration;
using FineUICore;
using Microsoft.Extensions.Logging;
using Microsoft.AspNetCore.Authentication.Cookies;
using System.Text.Encodings.Web;
using System.Text.Unicode;
using Microsoft.Extensions.FileProviders;
using System.IO;
using Model;

namespace Som
{
    public class Startup
    {
        public IConfiguration Configuration { get; }
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        // This method gets called by the runtime. Use this method to add services to the container.
        // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddSignalR();
            services.AddDistributedMemoryCache();
            services.AddSession();

            // FineUI 和 MVC 服务
            services.AddFineUI(Configuration);
            services.AddMvc(options =>
            {
                // 自定义模型绑定(Newtonsoft.Json)
                options.ModelBinderProviders.Insert(0, new JsonModelBinderProvider());
            });
            services.AddMvc().AddJsonOptions(options =>
            {
                options.SerializerSettings.DateFormatString = "yyyy-MM-dd HH:mm:ss";//将日期格式序列化
            });
			
			//添加dbcontext服务,可以实现依赖注入
			services.AddDbContext<SomDbContext>(options =>
            {
				/*
						[
							  "SomConfig":{
								"DataBase": "部署库",
								"Port": "8090"
							  },
							  "ConnectionStrings":{
								"DefaultConnection":"Data Source=(localdb)\MSSQLLocalDB;Initial Catalog=master;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=False"
							  }
						]
				*/
				var connStr=Configuration["ConnectionStrings:DefaultConnection"];//是写在Config.json文件里的 : 冒号表示 获取到第二层
				var  connstr2=Configuration.GetConnectionString("DefaultConnection");//另一种获取方法 自动去Config.json文件里找ConnectionStrings属性
                optionsBuilder.UseSqlServer(connstr2);
            });

            //添加认证Cookie信息
            services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
                .AddCookie(options =>
                {
                    options.LoginPath = new PathString("/login");
                    options.Cookie.HttpOnly = true;
                });

            services.AddAntiforgery(options =>
            {
                options.SuppressXFrameOptionsHeader = true;
            });

        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
        {
            //跨域支持
            app.UseCors(builder => builder.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader().AllowCredentials());
            app.UseSignalR(u => u.MapHub<Chat>("/chathub"));
            // 静态资源中间件
            app.UseStaticFiles(new StaticFileOptions
            {                //设置不限制content-type
                ServeUnknownFileTypes = true
            });
            app.UseSession();
            //验证中间件
            app.UseAuthentication();

            // FineUI 和 MVC 中间件(确保 UseFineUI 位于 UseMvc 的前面)
            app.UseFineUI();

            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Login/Error");
            }
            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "area",
                    template: "{area:exists}/{controller=Home}/{action=Index}/{id?}");
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");
            });
        }
    }
}

  以后在其后地址可以直接在构造函数里实现SomDbContext 对象的依赖注入

namespace EF_2._1
{
   public class EFStrudentService
    {
       private readonly SomDbContext _efDbContext;
       public EFStrudentService(SomDbContext context)
       {
           //这里实现了依赖注入
           this._efDbContext = context;
       }
       public void AddStudent(Student s)
       {
           _efDbContext.Add(s);
           _efDbContext.save();
       }
    }
}

  

上一篇:tomcat.apache startup.bat闪退两种解决方法


下一篇:解决tomcat启动startup.bat一闪而过的问题