首页 > 解决方案 > 从 Visual Studio 2019 运行时在 IIS Express 上获取 NullReferenceException

问题描述

我正在尝试对数据库(托管在远程服务器上的 Oracle18c)中的表进行 CRUD 操作 - “Items”,其中包含 item 和 UnitWeight 作为列。这是我的第一个 ASP.NET 项目。只需按照我在网上找到的教程(https://www.c-sharpcorner.com/blogs/crud-operation-in-asp-net-core30-with-oracle-database2)。我能够毫无问题地遵循这些步骤。但是当我尝试在 IIS Express 中运行该项目时,我在图片中遇到了以下错误。我不确定我做错了什么。

在此处输入图像描述

我在下面给出我的片段。

Items.cs [模型]

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

namespace cs550.Models
{
public class Items
    {
    public string item { get; set; }
    public int unitWeight { get; set; }

    }
}

itemService.CS [服务]

using cs550.Interface;
using cs550.Models;
using Microsoft.Extensions.Configuration;
using Oracle.ManagedDataAccess.Client;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace cs550.Services
{
    public class itemService : IItemService
    {
        private readonly string _connectionString;
        public itemService(IConfiguration _configuration)
        {
            _connectionString = _configuration.GetConnectionString("OracleDBConnection");
        }
        public IEnumerable<Items> getAllItem()
        {
            List<Items> itemList = new List<Items>();
             using (OracleConnection con = new OracleConnection(_connectionString))
        {
            using (OracleCommand cmd = con.CreateCommand())
            {
                    con.Open();
                    cmd.BindByName = true;
                    cmd.CommandText = "Select item, unitWeight from Items";
                    OracleDataReader rdr = cmd.ExecuteReader();
                    while(rdr.Read())
                    {
                        Items item = new Items
                        {
                            item = rdr["item"].ToString(),
                            unitWeight = Convert.ToInt32(rdr["unitWeight"])

                        };
                        itemList.Add(item);
                    }
                }
            }
            return itemList;
        }

    public Items getItemByItem(string it)
    {
        Items items = new Items();
         using (OracleConnection con = new OracleConnection(_connectionString))
        {
            using (OracleCommand cmd = con.CreateCommand())
            {
                con.Open();
                cmd.BindByName = true;
                cmd.CommandText = "Select item, unitWeight from Items Where item="+it+"";
                OracleDataReader rdr = cmd.ExecuteReader();
                while (rdr.Read())
                {
                    items.item = rdr["item"].ToString();
                    items.unitWeight = Convert.ToInt32(rdr["unitWeight"]);
                }
            }

            return items;
        }
    }
    
    public void AddItems(Items it)
    {
        try
        {
             using (OracleConnection con = new OracleConnection(_connectionString))
        {
            using (OracleCommand cmd = con.CreateCommand())
            {
                    con.Open();
                    cmd.CommandText = "Insert into Items(item, unitWeight) Values('"+it.item+"',"+it.unitWeight+")";
                    cmd.ExecuteNonQuery();
                }
            }
        }
        catch (Exception)
        {
            throw;
        }
    }

    public void EditItems(Items it)
    {
        try
        {
             using (OracleConnection con = new OracleConnection(_connectionString))
        {
            using (OracleCommand cmd = con.CreateCommand())
            {
                    con.Open();
                    cmd.CommandText = "Update Items Set unitWeight="+it.unitWeight+" where item='"+it.item+"'";
                    cmd.ExecuteNonQuery();
                }
            }
        }
        catch (Exception)
        {
            throw;
        }
    }
}
}

IItemService.cs [接口]

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

namespace cs550.Interface
{
    public interface IItemService
    {
        IEnumerable<Items> getAllItem();
        Items getItemByItem(string it);

        void AddItems(Items it);

        public void EditItems(Items it);
    }
}

启动程序

using cs550.Interface;
using cs550.Services;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

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

        public IConfiguration Configuration { get; }

    // This method gets called by the runtime. Use this method to add services to the container.
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddTransient<IItemService, itemService>();
        services.AddSingleton<IConfiguration>(Configuration);
        services.AddMvc().AddRazorPagesOptions(options =>
        {
            options.Conventions.AddPageRoute("/Items/Index", "");
        });
    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
        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.UseRouting();

        app.UseAuthorization();

        app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllerRoute(
                name: "default",
                pattern: "{controller=Items}/{action=Index}/{item?}");
        });
    }
}
}

应用设置.JSON

{
"Logging": {
  "LogLevel": {
    "Default": "Information",
    "Microsoft": "Warning",
    "Microsoft.Hosting.Lifetime": "Information"
  }
},
"ConnectionStrings": {
  "OracleDBConnection": "User Id=myUserID;Password=myPassword; Data Source= remoteURL:1521/DB"
},
"AllowedHosts": "*"
}

项目控制器.cs

using cs550.Interface;
using cs550.Models;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace cs550.Controllers
{
    public class ItemsController : Controller
    {
        IItemService itemService;

        public ItemsController(IItemService _itemService)
        {
            itemService = _itemService;
        }

        public ActionResult Index()
        {
            IEnumerable<Items> items = itemService.getAllItem();
            return View();
        }

    public ActionResult Create()
    {
        return View();
    }

    [HttpPost]
    public ActionResult Create(Items it)
    {
        itemService.AddItems(it);
        return RedirectToAction(nameof(Index));
    }

    public ActionResult Edit(string item)
    {
        Items it = itemService.getItemByItem(item);
        return View(it);
    }

    [HttpPost]
    public ActionResult Edit(Items it)
    {
        itemService.EditItems(it);
        return RedirectToAction(nameof(Index));
    }
}
}

我的剃刀页面:

索引.cshtml

@model IEnumerable<cs550.Models.Items>

@{
    ViewData["Title"] = "Index";
}

<h1>Index</h1>

<p>
    <a asp-action="Create">Create New</a>
</p>
<table class="table">
    <thead>
        <tr>
            <th>
                @Html.DisplayNameFor(model => model.item)
            </th>
            <th>
                @Html.DisplayNameFor(model => model.unitWeight)
            </th>
            <th></th>
        </tr>
    </thead>
    <tbody>
@foreach (var item in Model) {
        <tr>
            <td>
                @Html.DisplayFor(modelItem => item.item)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.unitWeight)
            </td>
            <td>
                @Html.ActionLink("Edit", "Edit", new {  id=item  }) |
                @Html.ActionLink("Delete", "Delete", new {  id=item })
            </td>
        </tr>
}
    </tbody>
</table>

创建.cshtml

@model cs550.Models.Items

@{
    ViewData["Title"] = "Create";
}

<h1>Create</h1>

<h4>Items</h4>
<hr />
<div class="row">
    <div class="col-md-4">
        <form asp-action="Create">
            <div asp-validation-summary="ModelOnly" class="text-danger"></div>
            <div class="form-group">
                <label asp-for="item" class="control-label"></label>
                <input asp-for="item" class="form-control" />
                <span asp-validation-for="item" class="text-danger"></span>
            </div>
            <div class="form-group">
                <label asp-for="unitWeight" class="control-label"></label>
                <input asp-for="unitWeight" class="form-control" />
                <span asp-validation-for="unitWeight" class="text-danger"></span>
            </div>
            <div class="form-group">
                <input type="submit" value="Create" class="btn btn-primary" />
            </div>
        </form>
    </div>
</div>

<div>
    <a asp-action="Index">Back to List</a>
</div>

@section Scripts {
    @{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
}

编辑.cshtml

@model cs550.Models.Items

@{
    ViewData["Title"] = "Edit";
}

<h1>Edit</h1>

<h4>Items</h4>
<hr />
<div class="row">
    <div class="col-md-4">
        <form asp-action="Edit">
            <div asp-validation-summary="ModelOnly" class="text-danger"></div>
            <div class="form-group">
                <label asp-for="item" class="control-label"></label>
                <input asp-for="item" class="form-control" />
                <span asp-validation-for="item" class="text-danger"></span>
            </div>
            <div class="form-group">
                <label asp-for="unitWeight" class="control-label"></label>
                <input asp-for="unitWeight" class="form-control" />
                <span asp-validation-for="unitWeight" class="text-danger"></span>
            </div>
            <div class="form-group">
                <input type="submit" value="Save" class="btn btn-primary" />
            </div>
        </form>
    </div>
</div>

<div>
    <a asp-action="Index">Back to List</a>
</div>

@section Scripts {
    @{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
}

标签: c#asp.net-core.net-corevisual-studio-2019iis-express

解决方案


    Change:
     using (OracleConnection con = new OracleConnection(_connectionString))
            {
                using (OracleCommand cmd = new OracleCommand())
                {
                

到:

      using(OracleConnection con = new OracleConnection(_connectionString))
     {  
              using(OracleCommand cmd = con.CreateCommand())
              {   

您必须在数据阅读器中使用 PL/SQL 文本,或者您可以创建存储过程并使用引用游标来处理数据

也改变:

public class itemController : Controller

public class ItemsController : Controller

更改您的操作索引代码:

 public ActionResult Index()
        {
            IEnumerable<Items> items = itemService.getAllItem();
            return View(items);
        }

推荐阅读