An unhandled exception occurred while processing the request. ASP.Net C#
Всем привет, решил начать изучать ASP.Net для примера взал проект с ютуба, сделал всё как по примеру, но выводит такую ошибку An unhandled exception occurred while processing the request. Также при преходе по /Car/List должен вывестить список автомобилей, но пишет 404. Подскажите что делать.
TypeLoadException: Could not load type 'System.Web.HttpContextBase' from assembly 'System.Web, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a'. System.Signature.GetSignature(Void* pCorSig, int cCorSig, RuntimeFieldHandleInternal fieldHandle, IRuntimeMethodInfo methodHandle, RuntimeType declaringType) System.Reflection.RuntimePropertyInfo.get_Signature() System.Reflection.RuntimePropertyInfo.get_PropertyType() Microsoft.Extensions.Internal.PropertyHelper.IsRefStructProperty(PropertyInfo property) Microsoft.Extensions.Internal.PropertyHelper.IsInterestingProperty(PropertyInfo property) Microsoft.Extensions.Internal.PropertyHelper+<>c.b__42_0(PropertyInfo p) System.Linq.Enumerable+WhereSelectArrayIterator<TSource, TResult>.ToArray() System.Linq.Enumerable.ToArray(IEnumerable source) Microsoft.Extensions.Internal.PropertyHelper.GetProperties(Type type, Func<PropertyInfo, PropertyHelper> createPropertyHelper, ConcurrentDictionary<Type, PropertyHelper[]> cache) Microsoft.Extensions.Internal.PropertyHelper.GetProperties(Type type) Microsoft.AspNetCore.Mvc.ApplicationModels.DefaultApplicationModelProvider.OnProvidersExecuting(ApplicationModelProviderContext context) Microsoft.AspNetCore.Mvc.ApplicationModels.ApplicationModelFactory.CreateApplicationModel(IEnumerable controllerTypes) Microsoft.AspNetCore.Mvc.ApplicationModels.ControllerActionDescriptorProvider.GetDescriptors() Microsoft.AspNetCore.Mvc.ApplicationModels.ControllerActionDescriptorProvider.OnProvidersExecuting(ActionDescriptorProviderContext context) Microsoft.AspNetCore.Mvc.Infrastructure.DefaultActionDescriptorCollectionProvider.UpdateCollection() Microsoft.AspNetCore.Mvc.Infrastructure.DefaultActionDescriptorCollectionProvider.Initialize() Microsoft.AspNetCore.Mvc.Infrastructure.DefaultActionDescriptorCollectionProvider.get_ActionDescriptors() Microsoft.AspNetCore.Mvc.Routing.AttributeRoute.GetTreeRouter() Microsoft.AspNetCore.Mvc.Routing.AttributeRoute.RouteAsync(RouteContext context) Microsoft.AspNetCore.Routing.RouteCollection.RouteAsync(RouteContext context) Microsoft.AspNetCore.Builder.RouterMiddleware.Invoke(HttpContext httpContext) Microsoft.AspNetCore.Diagnostics.StatusCodePagesMiddleware.Invoke(HttpContext context) Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)
launchSettings.json
{
"iisSettings": {
"windowsAuthentication": false,
"anonymousAuthentication": true,
"iisExpress": {
"applicationUrl": "http://localhost:50243",
"sslPort": 44363
}
},
"profiles": {
"IIS Express": {
"commandName": "IISExpress",
"launchBrowser": true,
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
},
"Shop": {
"commandName": "Project",
"launchBrowser": true,
"applicationUrl": "https://localhost:5001;http://localhost:5000",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
}
}
}
/Controllers/CarsController.cs
using Shop.Data.Interfaces;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Web.Mvc;
namespace Shop.Controllers
{
//имеюбтся различные функции которые возвращают обьект типа ViewResult - html страничка, которая будет отображаться на сайте
public class CarsController : Controller
{
private readonly IAllCars _allCars;
private readonly ICarsCategory _allCategories;
public CarsController(IAllCars iAllCars, ICarsCategory iCarsCat)
{
_allCars = iAllCars;
_allCategories = iCarsCat;
}
public ViewResult List()
{
var cars = _allCars.Cars;
return View(cars);
}
}
}
Data/Interfaces/IAllCars.cs
using Shop.Data.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace Shop.Data.Interfaces
{
public interface IAllCars
{
IEnumerable<Car> Cars { get; }
IEnumerable<Car> getFavCars { get; set; }
Car getObjectCar(int carId);
}
}
Data/Interfaces/ICarsCategory.cs
using Shop.Data.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace Shop.Data.Interfaces
{
public interface ICarsCategory
{
IEnumerable<Category> AllCategories { get; }
}
}
mocks/MockCars.cs
using Shop.Data.Interfaces;
using Shop.Data.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace Shop.Data.mocks
{
public class MockCars : IAllCars
{
private readonly ICarsCategory _categoryCars = new MockCategory();
public IEnumerable<Car> Cars
{
get
{
return new List<Car> {
new Car {
name = "Tesla Model s",
shortDesc = "Быстрый автомобиль",
longDesc = "Красивый, быстрый и очень тихий автомобиль компании Tesla",
img = "https://3dnews.ru/assets/external/illustrations/2020/09/23/1021277/tesla1.jpg",
price = 45000,
isFavorite = true,
available = true,
Category = _categoryCars.AllCategories.First()
},
new Car {
name = "Ford Fiesta",
shortDesc = "Тихий и спокойный",
longDesc = "Удобный автомобиль для городской жизни",
img = "https://images.drive.ru/i/0/5edf7d15ec05c4ff2d000004.jpg",
price = 11000,
isFavorite = false,
available = true,
Category = _categoryCars.AllCategories.Last()
},
new Car {
name = "BMW M3",
shortDesc = "Дерзский и стильный",
longDesc = "Удобный автомобиль для городской жизни",
img = "https://s0.rbk.ru/v6_top_pics/media/img/8/26/756007603497268.jpg",
price = 65000,
isFavorite = true,
available = true,
Category = _categoryCars.AllCategories.Last()
},
new Car {
name = "Mercedes C class",
shortDesc = "Уютный и большой",
longDesc = "Удобный автомобиль для городской жизни",
img = "https://kolesa-uploads.ru/-/014fd85f-2941-416d-b125-ad45299042bc/mercedes-benz-c-class-front2.jpg",
price = 40000,
isFavorite = false,
available = false,
Category = _categoryCars.AllCategories.Last()
},
new Car {
name = "Nissan Leaf",
shortDesc = "Бесшумный и экономичный",
longDesc = "Удобный автомобиль для городской жизни",
img = "https://images.drive.ru/i/0/5ab4f18aec05c4697d00008c.jpg",
price = 14000,
isFavorite = true,
available = true,
Category = _categoryCars.AllCategories.First()
},
};
}
}
public IEnumerable<Car> getFavCars { get; set ; }
public Car getObjectCar(int carId)
{
throw new NotImplementedException();
}
}
}
mocks/MockCategory.cs
using Shop.Data.Interfaces;
using Shop.Data.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace Shop.Data.mocks
{
public class MockCategory : ICarsCategory
{
public IEnumerable<Category> AllCategories
{
get
{
return new List<Category>
{
new Category { categoryName = "Электромобили", desc = "Современный вид транспорта"},
new Category { categoryName = "Классические автомобили", desc = "Машины с двигателями внутреннего згорания"}
};
}
}
}
}
Models/Car.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace Shop.Data.Models
{
public class Car
{
public int id { get; set; }
public string name { get; set; }
public string shortDesc { get; set; }
public string longDesc { get; set; }
public string img { get; set; }
public ushort price { get; set; }
public bool isFavorite { get; set; }
public bool available { get; set; }
public int categoryID { get; set; }
public virtual Category Category { get; set; }
}
}
Models/Category.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace Shop.Data.Models
{
public class Category
{
public int id { set; get; }
public string categoryName { set; get; }
public string desc { set; get; }
public List<Car> cars { set; get; }
}
}
Views/Cars/List.cshtml
@using Shop.Data.Models
@model IEnumerable<Car>
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<mate name="viewport" content="width=device-width" />
<title>List</title>
</head>
<body>
<h1>Все автомобили</h1>
@{
foreach(var car in Model)
{
<div>
<h2>Модель: @car.name</h2>
<p>Цена: @car.price.ToString("c")</p>
</div>
}
}
</body>
</html>
Program.cs
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace Shop
{
public class Program
{
public static void Main(string[] args)
{
CreateHostBuilder(args).Build().Run();
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
});
}
}
Startup.cs
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Shop.Data.Interfaces;
using Shop.Data.mocks;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace Shop
{
public class Startup
{
// 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) //для регистрации различных плагинов и модулей их надо регистрировать
{
services.AddTransient<IAllCars, MockCars>();
services.AddTransient<ICarsCategory, MockCategory>();
services.AddMvc(options => options.EnableEndpointRouting = false);
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
//отображение страничнки с ошибками
app.UseDeveloperExceptionPage();
//отображение кода странички (404, ...)
app.UseStatusCodePages();
app.UseStaticFiles();
//благодаря этой функции сможем отслеживать URL если не будет указан контроллер и та HTML страничка которая нужна, то будет использоваться URL по умолчанию
app.UseMvcWithDefaultRoute();
}
}
}