.net Core5的上下文+类原样输出+跨域

一、上下文操作

  创建Dal文件夹创建上下文类

  引用:using Microsoft.EntityFrameworkCore;

 public class AppDbcontext:DbContext
    {
        public AppDbcontext(DbContextOptions<AppDbcontext>options):base(options)
        {

        }

        public DbSet<UserModel> UserModels { get; set; }
        public DbSet<PullDoWnModel> PullDoWnModels { get; set; }
    }

  在Startup.cs

// This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            
            services.AddControllers()
                //类原样输出
                .AddJsonOptions(options =>options.JsonSerializerOptions.PropertyNamingPolicy=null);
            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new OpenApiInfo { Title = "Unit", Version = "v1" });
            });
            //添加上下文
            //添加引用using Microsoft.EntityFrameworkCore;
            services.AddDbContext<AppDbcontext>(options =>
            {
                //需要读取配置文件
                options.UseSqlServer(Configuration.GetConnectionString("MSSQL"));
            });

            //注入的三种方法
            //services.AddTransient<TService>(IServiceCollection);
            //一、AddTransient注入
            services.AddTransient<StudentDal>(); //会话

            //通过接口的方式进行注入
            services.AddTransient<IStudentDal, StudentDal>();

            //services.AddTransient(typeof(StudentDal));

            //二、AddSingleton注入 
            //services.AddSingleton<StudentDal>(); //单一模式

            //三、AddScoped注入
            //services.AddScoped<StudentDal>();//指定类型的范围内的服务添加到指定的 IServiceCollection 中


            //配置跨域
            services.AddCors(options =>
            {
                options.AddDefaultPolicy(p =>
                {
                    //AllowAnyOrigin 来源
                    //AllowAnyMethod 方法
                    //AllowAnyHeader 头部信息
                    p.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader();
                });
            });

        }

二、类原样输出

 services.AddControllers()
                //类原样输出
                .AddJsonOptions(options =>options.JsonSerializerOptions.PropertyNamingPolicy=null);

三、跨域

  1、下载安装包Microsoft.AspNetCore.Cors

  2、在Startup.cs进行使用

  3、引用:using Microsoft.AspNetCore.Cors;

services.AddCors(options =>
            {
                options.AddDefaultPolicy(p =>
                {
                    //AllowAnyOrigin 来源
                    //AllowAnyMethod 方法
                    //AllowAnyHeader 头部信息
                    p.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader();
                });
            });
            app.UseRouting();

            //使用跨域
            app.UseCors();

            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });

 

      ......待续

 

posted @ 2021-10-12 21:31  魔术人生  阅读(155)  评论(0编辑  收藏  举报
复制代码