(初识MVC Core)六、配置

1.说明

1)采用Key-Value键值对的形式进行配置

2)配置的存储方式可以通过内存、JSON、XML、INI、环境变量和启动参数等

3)配置系统解耦

4)优化了依赖注入

 

2.通过JSON进行配置(配置数据库连接)

1)创建appsettings.json、ConnectionOptions.cs

 

appsettings.json:

{
  "Logging": {
    "LogLevel": {
      "Defaule": "Warning"
    }
  },
  "ConnectionStrings": {
    "DefaultConnection": "Database=InMemory;"
  }
}

 ConnectionOptions.cs:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace CoreModelTwo.Settings
{
    public class ConnectionOptions
    {
        public string DefaultConnection { get; set; }
    }
}

 

2)依赖注入获取配置文件信息(红色部分)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using CoreModelTwo.Services;
using CoreModelTwo.Settings;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;

namespace CoreModelTwo
{
    public class Startup
    {
        private readonly IConfiguration _configuration;

        //构造函数注入
        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)
        {
            //注册MVC所需要的相关服务到IoC容器里
            services.AddMvc();

            //使用Singleton进行IoC依赖注入(每当有请求IMovieService都会返回MovieService实例)
            services.AddSingleton<IMovieService,MovieService>();
            services.AddSingleton<ICinemaService, CinemaService>();

            //获取appsettings.json的配置信息
            services.Configure<ConnectionOptions>(_configuration.GetSection("ConnectionStrings"));
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env,ILogger<Startup> logger)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            #region 配置路由

            //将错误显示在页面
            app.UseStatusCodePages();
            //跳转到指定错误位置
            //app.UseStatusCodePagesWithRedirects("/Error");         

            //加载wwwroot里头的文件(使用此可以加载出来)
            app.UseStaticFiles();

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

            #endregion

        }
    }
}

 

 

 

注:

 

3.在CinemaController.cs里头通过强类型ConnectionOptions.cs获取配置参数

using CoreModel;
using CoreModelTwo.Services;
using CoreModelTwo.Settings;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Options;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace CoreModelTwo.Controllers
{
    public class CinemaController : Controller
    {
        private readonly ICinemaService _cinemaService;
        private readonly IOptions<ConnectionOptions> _options;

        public CinemaController(ICinemaService cinemaService,IOptions<ConnectionOptions> options)
        {
            _cinemaService = cinemaService;
            _options = options;

        }

        public async Task<IActionResult> Index()
        {
            ViewBag.Title = "电影院列表";
            return View(await _cinemaService.GetAllAsync());
        }

        public IActionResult Add()
        {
            ViewBag.Title = "添加电影院";
            return View(new Cinema());
        }

        [HttpPost]
        public async Task<IActionResult> Add(Cinema model)
        {
            if (ModelState.IsValid)
            {
                await _cinemaService.AddAsync(model);
            }
            return RedirectToAction("Index");
        }

        public async Task<IActionResult> Edit(int cinemaId)
        {
            var exist = await _cinemaService.GetCinemaById(cinemaId);
            return View(exist);
        }

        [HttpPost]
        public async Task<IActionResult> Edit(int Id, Cinema model)
        {
            if (ModelState.IsValid)
            {
                var exist = await _cinemaService.GetCinemaById(Id);
                if (exist == null)
                {
                    return NotFound();
                }
                exist.Name = model.Name;
                exist.Location = model.Location;
                exist.Capacity = model.Capacity;
            }
            return RedirectToAction("Index");
        }

    }
}

调试获得:

当然也可以使用页面去获取(红色部分)

@model IEnumerable<CoreModel.Cinema> 
@using CoreModelTwo.Settings
@using Microsoft.Extensions.Options

@inject IOptions<ConnectionOptions> options
<div class="container">
    <div class="row">
        <table class="table table-bordered">
            <caption></caption>
            <thead class="thead-dark">
                <tr>
                    <th scope="col">编码</th>
                    <th scope="col">电影院名称</th>
                    <th scope="col">地址</th>
                    <th scope="col">容量</th>
                    <th scope="col">操作</th>
                    <th scope="col">@options.Value.DefaultConnection</th>
                </tr>
            </thead>
            <tbody>
                @Html.DisplayForModel()
            </tbody>
        </table>
        <a asp-controller="Cinema" asp-action="Add">添加</a>
    </div>
</div>

结果显示:

 参阅:https://v.qq.com/x/page/x0750why9sm.html

 谢谢Dave

 

posted @ 2019-03-24 23:05  蜗牛的礼物  阅读(316)  评论(0编辑  收藏  举报