Получение исключения NullReferenceException в IIS Express при запуске из Visual Studio 2019

#c# #asp.net-core #visual-studio-2019 #iis-express #oracle18c

#c# #asp.net-core #.net-ядро #visual-studio-2019 #iis-express

Вопрос:

Я пытаюсь выполнить операцию CRUD над таблицей из базы данных (Oracle18c, размещенной на удаленном сервере) — «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);
    }
}
 

Strtup.CS

 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?}");
        });
    }
}
}
 

appsetting.JSON

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

ItemController.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));
    }
}
}
 

My Razor Pages:

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> 

Create.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");}
} 

Комментарии:

1. Где находится ваш контроллер и как вы делаете запрос?

2. @MestreDosMagros Извиняется! Обновлен поток с информацией о контроллере

3. Ваш cmd не привязан к соединению. В примере / руководстве используется cmd = con.CreateCommand() то, что вы используете cmd = new OracleCommand() .

Ответ №1:

     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);
        }
 

Комментарии:

1. Спасибо! Это сработало. Но теперь я получаю другую ошибку.

2. Исключение недопустимой операции. Обновлен поток с изображением

3. Вы должны использовать текст PL / SQL в вашем устройстве чтения данных, или вы можете создать хранимую процедуру и использовать курсор и входные параметры для получения данных

4. Спасибо за предложение, я передал эту ошибку, но теперь получаю что-то еще : (

5. Проверьте мой ответ еще раз.

Ответ №2:

Error 404 Not Found это ошибка на стороне клиента, в которой указывается, что ресурс, который вы ищете, не найден. Здесь находится ресурс, который вы ищете Index items .
В Startup.cs вы упомянули маршрут как {controller=Items}/{action=Index}/{item?} . Поэтому при загрузке он будет искать контроллер с именем as Items , а затем Index будет выполнено действие. Здесь имя контроллера отличается, item и, следовательно Index , действие не может быть найдено. Поэтому изменение его на правильное имя контроллера на public class ItemsController : Controller устранит 404 проблему.
Пожалуйста, добавьте http-глаголы (Post, Get, Put, Delete) в действия, если вы хотите использовать его в маршрутах. Здесь в некоторых методах, например Edit , отсутствуют эти глаголы.
Еще одна вещь, на которую следует обратить внимание: здесь вы не добавляете никаких страниц razor, поэтому я ожидаю, что вы будете вызывать маршрут непосредственно в браузере или с помощью такого инструмента, как postman / fiddler. Поэтому, когда вы запускаете IISExpress, он перейдет к localhost:<port number> тому, который сопоставлен с маршрутом по умолчанию. Поэтому, если вы хотите получить доступ к какому-либо конкретному действию, пожалуйста, измените метод вызова, например Get или Post, и добавьте правильный путь маршрутизации.

Комментарии:

1. Спасибо за подробное объяснение. Я добавил страницы razor, обновил поток