Asp.net core ASP.Net核心-设置和获取会话变量

Asp.net core ASP.Net核心-设置和获取会话变量,asp.net-core,Asp.net Core,我有一个使用ASP.NET内核、Angular 5和ADO.NET的应用程序 在我决定更改代码以使用从appssettings.json文件获取的数据库连接字符串设置会话变量之前,它工作得很好 我将此作为参考: 但是,当我尝试设置会话变量时,我在SetSessionVariable()方法中得到一个空对象引用 错误是: 启动应用程序时出错。 NullReferenceException:对象引用未设置为 对象Startup.cs中的Angular5NetcoreAdo.Startup.SetSe

我有一个使用ASP.NET内核、Angular 5和ADO.NET的应用程序

在我决定更改代码以使用从appssettings.json文件获取的数据库连接字符串设置会话变量之前,它工作得很好

我将此作为参考:

但是,当我尝试设置会话变量时,我在SetSessionVariable()方法中得到一个空对象引用

错误是:

启动应用程序时出错。 NullReferenceException:对象引用未设置为 对象Startup.cs中的Angular5NetcoreAdo.Startup.SetSessionVariable(), 第82行

我的代码是:

using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.SpaServices.AngularCli;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Angular5NetcoreAdo.Models;

// Added these.
using Microsoft.AspNetCore.Http;
using System;

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

    public IConfiguration Configuration { get; }

    // Added this.
    public HttpContext HttpContext { get; }

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);

        // In production, the Angular files will be served from this directory.
        services.AddSpaStaticFiles(configuration =>
        {
            configuration.RootPath = "ClientApp/dist";
        });

        services.AddScoped<EmployeeDataAccessLayer>();

        // Added this.
        services.AddSession(options =>
        {
            options.Cookie.Name = ".ConnectionString";
        });

        // Added this.
        SetSessionVariable();
    }

    // Added this.
    public void SetSessionVariable()
    {
         HttpContext.Session.SetString("ConnectionString", Convert.ToString(Configuration.GetConnectionString("DBAngular5NetcoreAdoDatabase")));
    }

    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
        else
        {
            app.UseExceptionHandler("/Error");
        }

        app.UseStaticFiles();
        app.UseSpaStaticFiles();

        // Added this.
        app.UseSession();

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

        app.UseSpa(spa =>
        {
            spa.Options.SourcePath = "ClientApp";

            if (env.IsDevelopment())
            {
                spa.UseAngularCliServer(npmScript: "start");
            }
        });
    }
}
------------------现在添加为引用此类的新错误

using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using Microsoft.Extensions.Configuration;
using Microsoft.AspNetCore.Http;

namespace Angular5NetcoreAdo.Models
{
    public class EmployeeDataAccessLayer
    {
       public HttpContext HttpContext { get; }
       public string connectionString;

       public EmployeeDataAccessLayer(HttpContext httpContext)
       {
           // Set the property.
           HttpContext = httpContext;

           // Get the connection string session variable.
           connectionString = HttpContext.Session.GetString("ConnectionString");
       }

       public IEnumerable<Employee> GetAllEmployees()
       {
          try
           {
               List<Employee> lstemployee = new List<Employee>();

               using (SqlConnection con = new SqlConnection(connectionString))
               {
                   SqlCommand cmd = new SqlCommand("SelectEmployees", con);
                   cmd.CommandType = CommandType.StoredProcedure;

                   con.Open();

                   SqlDataReader rdr = cmd.ExecuteReader();

                   while (rdr.Read())
                   {
                       Employee employee = new Employee();

                       employee.ID = Convert.ToInt32(rdr["EmployeeID"]);
                       employee.Name = rdr["Name"].ToString();
                       employee.Gender = rdr["Gender"].ToString();
                       employee.Department = rdr["Department"].ToString();
                       employee.City = rdr["City"].ToString();

                       lstemployee.Add(employee);
                   }

                   rdr.Close();
                   con.Close();
               }

               return lstemployee;
           }
           catch
           {
               throw;
           }
       }

       public Employee GetEmployeeData(int id)
       {
           try
           {
               Employee employee = new Employee();

               using (SqlConnection con = new SqlConnection(connectionString))
               {
                   SqlCommand cmd = new SqlCommand("SelectEmployeeById", con);
                   cmd.CommandType = CommandType.StoredProcedure; 
                   cmd.Parameters.AddWithValue("@EmpId", id);

                   con.Open();

                   SqlDataReader rdr = cmd.ExecuteReader();

                   while (rdr.Read())
                   {
                       employee.ID = Convert.ToInt32(rdr["EmployeeID"]);
                       employee.Name = rdr["Name"].ToString();
                       employee.Gender = rdr["Gender"].ToString();
                       employee.Department = rdr["Department"].ToString();
                       employee.City = rdr["City"].ToString();
                   }

                   rdr.Close();
                   con.Close();
               }

               return employee;
           }
           catch
           {
               throw;
           }
       }

       public int AddEmployee(Employee employee)
       {
           try
           {
               using (SqlConnection con = new SqlConnection(connectionString))
               {
                   SqlCommand cmd = new SqlCommand("InsertEmployee", con);
                   cmd.CommandType = CommandType.StoredProcedure;

                   cmd.Parameters.AddWithValue("@Name", employee.Name);
                   cmd.Parameters.AddWithValue("@City", employee.City);
                   cmd.Parameters.AddWithValue("@Department", employee.Department);
                   cmd.Parameters.AddWithValue("@Gender", employee.Gender);

                   con.Open();

                   cmd.ExecuteNonQuery();

                   con.Close();
               }

               return 1;
           }
           catch
           {
               throw;
           }
       }

       public int UpdateEmployee(Employee employee)
       {
           try
           {
               using (SqlConnection con = new SqlConnection(connectionString))
               {
                   SqlCommand cmd = new SqlCommand("UpdateEmployee", con);
                   cmd.CommandType = CommandType.StoredProcedure;

                   cmd.Parameters.AddWithValue("@EmpId", employee.ID);
                   cmd.Parameters.AddWithValue("@Name", employee.Name);
                   cmd.Parameters.AddWithValue("@City", employee.City);
                   cmd.Parameters.AddWithValue("@Department", employee.Department);
                   cmd.Parameters.AddWithValue("@Gender", employee.Gender);

                   con.Open();

                   cmd.ExecuteNonQuery();

                    con.Close();
               }

               return 1;
           }
           catch
           {
               throw;
           }
       }

       public int DeleteEmployee(int id)
       {
           try
           {
            using (SqlConnection con = new SqlConnection(connectionString))
               {
                   SqlCommand cmd = new SqlCommand("DeleteEmployee", con);
                   cmd.CommandType = CommandType.StoredProcedure;
                   cmd.Parameters.AddWithValue("@EmpId", id);

                   con.Open();

                   cmd.ExecuteNonQuery();

                    con.Close();
              }

               return 1;
          }
        catch
           {
               throw;
           }
       }
   }
}
使用系统;
使用System.Collections.Generic;
使用系统数据;
使用System.Data.SqlClient;
使用Microsoft.Extensions.Configuration;
使用Microsoft.AspNetCore.Http;
命名空间Angular5NetcoreAdo.Models
{
公共类EmployeeDataAccessLayer
{
公共HttpContext HttpContext{get;}
公共字符串连接字符串;
公共EmployeeDataAccessLayer(HttpContext HttpContext)
{
//设置属性。
HttpContext=HttpContext;
//获取连接字符串会话变量。
connectionString=HttpContext.Session.GetString(“connectionString”);
}
公共IEnumerable GetAllEmployees()
{
尝试
{
List lstemployee=新列表();
使用(SqlConnection con=newsqlconnection(connectionString))
{
SqlCommand cmd=newsqlcommand(“SelectEmployees”,con);
cmd.CommandType=CommandType.storedProcess;
con.Open();
SqlDataReader rdr=cmd.ExecuteReader();
while(rdr.Read())
{
员工=新员工();
employee.ID=Convert.ToInt32(rdr[“EmployeeID]”);
employee.Name=rdr[“Name”].ToString();
employee.Gender=rdr[“Gender”].ToString();
employee.Department=rdr[“Department”].ToString();
employee.City=rdr[“City”].ToString();
lstmemployee.Add(employee);
}
rdr.Close();
con.Close();
}
返回员工;
}
抓住
{
投掷;
}
}
公共雇员GetEmployeeData(内部id)
{
尝试
{
员工=新员工();
使用(SqlConnection con=newsqlconnection(connectionString))
{
SqlCommand cmd=newsqlcommand(“SelectEmployeeById”,con);
cmd.CommandType=CommandType.storedProcess;
cmd.Parameters.AddWithValue(“@EmpId”,id);
con.Open();
SqlDataReader rdr=cmd.ExecuteReader();
while(rdr.Read())
{
employee.ID=Convert.ToInt32(rdr[“EmployeeID]”);
employee.Name=rdr[“Name”].ToString();
employee.Gender=rdr[“Gender”].ToString();
employee.Department=rdr[“Department”].ToString();
employee.City=rdr[“City”].ToString();
}
rdr.Close();
con.Close();
}
返回员工;
}
抓住
{
投掷;
}
}
公共整数加法雇员(雇员)
{
尝试
{
使用(SqlConnection con=newsqlconnection(connectionString))
{
SqlCommand cmd=newsqlcommand(“InsertEmployee”,con);
cmd.CommandType=CommandType.storedProcess;
cmd.Parameters.AddWithValue(“@Name”,employee.Name);
cmd.Parameters.AddWithValue(“@City”,employee.City);
cmd.Parameters.AddWithValue(“@Department”,employee.Department);
cmd.Parameters.AddWithValue(“@Gender”,employee.Gender);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
返回1;
}
抓住
{
投掷;
}
}
public int UpdateEmployee(员工)
{
尝试
{
使用(SqlConnection con=newsqlconnection(connectionString))
{
SqlCommand cmd=newsqlcommand(“UpdateEmployee”,con);
cmd.CommandType=CommandType.storedProcess;
cmd.Parameters.AddWithValue(“@EmpId”,employee.ID);
cmd.Parameters.AddWithValue(“@Name”,employee.Name);
cmd.Parameters.AddWithValue(“@City”,employee.City);
cmd.Parameters.AddWithValue(“@Department”,employee.Department);
cmd.Parameters.AddWithValue(“@Gender”,employee.Gender);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
返回1;
}
抓住
{
投掷;
}
}
公共内部删除员工(内部id)
{
尝试
{
使用(SqlConnection con=newsqlconnection(connectionString))
{
SqlCommand cmd=新的SqlCommand(“deletemployee”,con);
cmd.CommandType=CommandType.storedProcess;
cmd.Parameters.AddWithValue(“@EmpId”,id);
con.Open();
cmd.ExecuteNonQuery();
app.UseSession();

// Call the middlware now to set the session variable with the database
// connection string from appsettings.json. 
app.UseRequestConnection();
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using Microsoft.Extensions.Configuration;
using Microsoft.AspNetCore.Http;

namespace Angular5NetcoreAdo.Models
{
    public class EmployeeDataAccessLayer
    {
       public HttpContext HttpContext { get; }
       public string connectionString;

       public EmployeeDataAccessLayer(HttpContext httpContext)
       {
           // Set the property.
           HttpContext = httpContext;

           // Get the connection string session variable.
           connectionString = HttpContext.Session.GetString("ConnectionString");
       }

       public IEnumerable<Employee> GetAllEmployees()
       {
          try
           {
               List<Employee> lstemployee = new List<Employee>();

               using (SqlConnection con = new SqlConnection(connectionString))
               {
                   SqlCommand cmd = new SqlCommand("SelectEmployees", con);
                   cmd.CommandType = CommandType.StoredProcedure;

                   con.Open();

                   SqlDataReader rdr = cmd.ExecuteReader();

                   while (rdr.Read())
                   {
                       Employee employee = new Employee();

                       employee.ID = Convert.ToInt32(rdr["EmployeeID"]);
                       employee.Name = rdr["Name"].ToString();
                       employee.Gender = rdr["Gender"].ToString();
                       employee.Department = rdr["Department"].ToString();
                       employee.City = rdr["City"].ToString();

                       lstemployee.Add(employee);
                   }

                   rdr.Close();
                   con.Close();
               }

               return lstemployee;
           }
           catch
           {
               throw;
           }
       }

       public Employee GetEmployeeData(int id)
       {
           try
           {
               Employee employee = new Employee();

               using (SqlConnection con = new SqlConnection(connectionString))
               {
                   SqlCommand cmd = new SqlCommand("SelectEmployeeById", con);
                   cmd.CommandType = CommandType.StoredProcedure; 
                   cmd.Parameters.AddWithValue("@EmpId", id);

                   con.Open();

                   SqlDataReader rdr = cmd.ExecuteReader();

                   while (rdr.Read())
                   {
                       employee.ID = Convert.ToInt32(rdr["EmployeeID"]);
                       employee.Name = rdr["Name"].ToString();
                       employee.Gender = rdr["Gender"].ToString();
                       employee.Department = rdr["Department"].ToString();
                       employee.City = rdr["City"].ToString();
                   }

                   rdr.Close();
                   con.Close();
               }

               return employee;
           }
           catch
           {
               throw;
           }
       }

       public int AddEmployee(Employee employee)
       {
           try
           {
               using (SqlConnection con = new SqlConnection(connectionString))
               {
                   SqlCommand cmd = new SqlCommand("InsertEmployee", con);
                   cmd.CommandType = CommandType.StoredProcedure;

                   cmd.Parameters.AddWithValue("@Name", employee.Name);
                   cmd.Parameters.AddWithValue("@City", employee.City);
                   cmd.Parameters.AddWithValue("@Department", employee.Department);
                   cmd.Parameters.AddWithValue("@Gender", employee.Gender);

                   con.Open();

                   cmd.ExecuteNonQuery();

                   con.Close();
               }

               return 1;
           }
           catch
           {
               throw;
           }
       }

       public int UpdateEmployee(Employee employee)
       {
           try
           {
               using (SqlConnection con = new SqlConnection(connectionString))
               {
                   SqlCommand cmd = new SqlCommand("UpdateEmployee", con);
                   cmd.CommandType = CommandType.StoredProcedure;

                   cmd.Parameters.AddWithValue("@EmpId", employee.ID);
                   cmd.Parameters.AddWithValue("@Name", employee.Name);
                   cmd.Parameters.AddWithValue("@City", employee.City);
                   cmd.Parameters.AddWithValue("@Department", employee.Department);
                   cmd.Parameters.AddWithValue("@Gender", employee.Gender);

                   con.Open();

                   cmd.ExecuteNonQuery();

                    con.Close();
               }

               return 1;
           }
           catch
           {
               throw;
           }
       }

       public int DeleteEmployee(int id)
       {
           try
           {
            using (SqlConnection con = new SqlConnection(connectionString))
               {
                   SqlCommand cmd = new SqlCommand("DeleteEmployee", con);
                   cmd.CommandType = CommandType.StoredProcedure;
                   cmd.Parameters.AddWithValue("@EmpId", id);

                   con.Open();

                   cmd.ExecuteNonQuery();

                    con.Close();
              }

               return 1;
          }
        catch
           {
               throw;
           }
       }
   }
}