繁体   English   中英

如何为我的 asp.net 核心 mvc 编写连接字符串

[英]How to write connection string for my asp.net core mvc

尽管我查看了许多解决方案,但似乎无法在我的 asp.net 核心 mvc 程序中应用或理解如何使用连接字符串。

这是我的 appsettings.json 文件:

{
  "Logging":{
    "Debug":{
      "LogLevel":{
        "Default":"Information"
      }
    },
    "AllowedHosts":"*",
    "ConnectionString":{
      "connectionString":"Server=W1571415\\MSSQLSERVER01;Database=***********;UserId=*********;Password=***********;"
    }
  },
  "dependencies":{
    "Microsoft.Extensions.Caching.Memory":"1.0.0",
    "Microsoft.AspNetCore.Session":"1.0.0"
  }
}

我的 startup.cs 文件代码:

using HospitalApp.Infrastructure;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Localization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Razor;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using System.Collections.Generic;
using System.Globalization;

//This file is for app behaviour
namespace HospitalApp
{
    /// <summary>
    /// Startup class contains the methods scuh as ConfigureServices which are used to configure the environment in which the application is running.
    /// </summary>
    public class Startup
    {
        private readonly ILogger _logger;

        /// <summary>
        /// The control from the Program.cs when it encounters the .UseStartup() comes here.It uses the parameters configuration of the type IConfiguration and logger of the type ILogger.
        /// </summary>
        public Startup(IConfiguration configuration, ILogger<Startup> logger)
        {
            Configuration = configuration;
            _logger = logger;
        }

        /// <summary>
        /// This method Configuration is of the type IConfiguration.
        /// </summary>
        public IConfiguration Configuration { get; }

        /// <summary>
        /// This method gets called by the runtime. Use this method to add services to the container.
        /// </summary>
        /// <param name="services">services is of the type IServiceCollection which is used specify the contract of collection to service descriptors.</param>
        public void ConfigureServices(IServiceCollection services)
        {
            services.Configure<CookiePolicyOptions>(options =>
            {
                // This lambda determines whether user consent for non-essential cookies is needed for a given request.
                options.CheckConsentNeeded = context => true;
                options.MinimumSameSitePolicy = SameSiteMode.None;
            });

            ////services.AddSession(so =>
            ////{
            ////    so.IdleTimeout = TimeSpan.FromSeconds(60);
            ////});

            services.AddLocalization(options => options.ResourcesPath = "Resources");
            services.AddMvc()
                        .SetCompatibilityVersion(CompatibilityVersion.Version_2_2)
                        .AddViewLocalization(
            LanguageViewLocationExpanderFormat.Suffix,
            options => { options.ResourcesPath = "Resources"; })
                        .AddDataAnnotationsLocalization();

            //dependency injection
            services.AddSingleton<IDbRepository, DbRepository>();
           
            //_logger.LogInformation("Added TodoRepository to services");
            services.AddDistributedMemoryCache(); // Adds a default in-memory implementation of IDistributedCache
            services.AddSession();


           
        }

        /// <summary>
        /// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        /// </summary>
        /// <param name="app">This is provides mechanism to confifure application's request pipeline.</param>
        /// <param name="env">Provides information about the webhsoting environment an application is running in.</param>
        /// <param name="loggerFactory">Represent a type used to configure the logging system.</param>
        /// <param name="logger">It is of the type ILogger which is a generic interface for logger.</param>
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, ILogger<Startup> logger)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
                loggerFactory.AddFile("Logs/mylog-{Date}.txt");
                _logger.LogInformation("In Development environment");
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
                // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
                app.UseHsts();
            }

            app.UseHttpsRedirection();
            app.UseStaticFiles();
            app.UseCookiePolicy();
            app.UseSession();

            var cultures = new List<CultureInfo>
            {
                new CultureInfo("en"),
                new CultureInfo("pt")
            };

            app.UseRequestLocalization(options => {
                options.DefaultRequestCulture = new RequestCulture("en-US");
                options.SupportedCultures = cultures;
                options.SupportedUICultures = cultures;
            });


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

而且我没有使用 DBContext 文件,所以这里是我的 Infrastrucutre 文件,其中包含文件 IDbRepostiory 和 DbRepository。 我必须在 DbRepostiory 文件中使用这个连接字符串。 那么,go怎么来呢?

 namespace HospitalApp.Infrastructure
{

    /// <summary>
    /// This class is used to establish a data connection with the MS SQL Server.
    
    /// The connectionString specified here stores the Database name and the Data Source specifies the server name.
    /// </summary>
    public class DbRepository : IDbRepository
    {
        /// HERE I NEED TO SPECIFY THE CONNECTION STRING FROM APPSETTING.JSON FILE.

        //string connectionString = "Integrated Security=SSPI;Persist Security Info=False;Initial Catalog=HospitalDummy;Data Source=W1571415\\MSSQLSERVER01;Application Name=Hospital";
        string connectionString = @"Server=W1571415\MSSQLSERVER01;Database=HospitalDummy;User Id=hospitaluser;Password=abc@123;";

        /// <summary>
        /// This function is used to display all the Patients data.  
        /// The patient's data is taken in the form of a list.
        /// SqlConnection is used to specify the connection of the connectionString with the Database.
        /// Here the Stored procedure spGetAllPatients is taken which is used to display the Patients details.
        /// </summary>
        /// <returns>It returns the details of the patient's in the form of a List.</returns>
        public List<Patient> GetAllPatients()
        {
            List<Patient> lstpatient = new List<Patient>();
          
            using (SqlConnection con = new SqlConnection(connectionString))
            {
                try
                {
                    SqlCommand cmd = new SqlCommand("dbo.spGetAllPatients", con);
                    cmd.CommandType = CommandType.StoredProcedure;
                    con.Open();
                    SqlDataReader rdr = cmd.ExecuteReader();

                    while (rdr.Read())
                    {
                        Patient patient = new Patient();
                        try
                        {
                            patient.PatientId = Convert.ToInt32(rdr["PatientId"]);
                            if (rdr["FullName"] != DBNull.Value)
                                patient.FullName = Convert.ToString(rdr["FullName"]);
                            if (rdr["Ailment"] != DBNull.Value)
                                patient.Ailment = Convert.ToString(rdr["Ailment"]);
                            if (rdr["Gender"] != DBNull.Value)
                                patient.Gender = Convert.ToString(rdr["Gender"]);
                            if (rdr["Status"] != DBNull.Value)
                                patient.Status = Convert.ToString(rdr["Status"]);
                            count = count + 1;
                            
                            if (patient.Status == "Active")
                            {
                                lstpatient.Add(patient);
                            }
                        }
                        catch (Exception e)
                        {
                           Console.WriteLine("Records not displayed properly. ",e);
                        }
                    }

                    con.Close();
                }
                catch (Exception e)
                {
                    Console.WriteLine("Failure in getting records properly. ", e);
                }
            }
}

这是IDbRepostiory文件供参考:

public interface IDbRepository
{
    /// <summary>
    /// This function is used to get the list of all Patients.
    /// </summary>
    /// <returns>It has a return type of list i.e. the Patient data that will be returned will be in the form of a list.</returns>
    List<Patient> GetAllPatients();
}

对此的概述是

一世。 确保您的DbRepository实现了一个接口 (IDbRepository, done),以便它可以作为服务调用,并包含一个用于接收任何配置数据的构造函数

ii. Startup.cs访问appsettings.json以检索 json 配置数据

iii. Startup.csDbRepository实例化为IDbRepository服务并将连接字符串作为参数传递

如果DbRepository继承自DbContext ,则可以添加这样的构造函数

public DbRepository(DbContextOptions<DbRepository> options) : base(options) 
{
}

Alternativelty,这里是你如何手动创建一个构造函数,为了更好的衡量,我添加了一个测试方法GetConnectionString()

public class DbRepository : IDbRepository
{
    private string _connectionString;

    public DbRepository(string connection)
    {
        _connectionString = connection;
    }

    public string GetConnectionString()
    {
        return _connectionString;
    }
}

Statup.cs 中查看构造函数如何访问appsetting.json并将数据存储在Configuration字段中

查看ConfigureServices如何调用IDbRepository服务并传递参数

using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using HospitalApp.Infrastructure;

namespace Test
{
    public class Startup
    {
        public IConfiguration Configuration { get; }

        public Startup(IHostingEnvironment env)
        {
            var builder = new ConfigurationBuilder()
                .SetBasePath(env.ContentRootPath)
                .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
                .AddEnvironmentVariables();
                Configuration = builder.Build();
        }

        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc();
            string connectionString = Configuration["ConnectionString:connectionString"];
            //  this is how a class inheriting dbcontext can be called
            //  services.AddDbContext<DbRepository>(options => options.UseSqlServer(connectionString));
            //  or call IDbRepository as a custom service
            services.AddScoped<IDbRepository>(repository => new DbRepository(connectionString));
        }

        public void Configure(IApplicationBuilder app, IHostingEnvironment env) { //  ... }
    }
}

想象一下,如果您的HomeController看起来像这样,通过它的构造函数接受IDbRepository服务的实例,因此它可以访问存储库并将连接字符串传递到 ViewBag

public class HomeController : Controller
{
    private readonly IDbRepository _dbrepository;

    public HomeController(IDbRepository dbrepository)
    {
        _dbrepository = dbrepository;
    }

    [HttpGet]
    public ViewResult Home()
    {
        ViewBag.ConnectionString = _dbrepository.GetConnectionString();
        return View("Home");
    }
}

Home.cshtml只需要包含以下内容即可证明成功

<h1>ConnectionString</h1>
<b>@ViewBag.ConnectionString</b>

在此处输入图像描述

在一个测试项目中得到确认——我第一次创建了一个接受参数的服务(以前只使用过 dbcontext),所以很高兴看到这个——希望这会有所帮助!

这是我的 appsettings.json

{
    "Logging": {
        "LogLevel": {
            "Default": "Information"
        }
    },
    "AllowedHosts": "*",
    "ConnectionString": {
        "connectionString": "Server=W1571415\\MSSQLSERVER01;Database=***********;UserId=*********;Password=***********;"
    },
    "dependencies": {
        "Microsoft.Extensions.Caching.Memory": "1.0.0",
        "Microsoft.AspNetCore.Session": "1.0.0"
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM