我无法从 .net core mvc web api 数据库中获取记录

I can't get records from .net core mvc web api database

我怎么也解决不了,你能帮忙吗? 我将 web api 添加到我的 .net core mvc 项目中。我可以 return 值作为字符串或 json,很正常。但是当涉及到数据库时,我遇到了问题。我收到一个空错误。无论我多么努力地寻找,我都无法弄清楚。最小的答案有很大帮助。

[ApiController] 当我添加它时,我的应用程序根本打不开。当我发表评论时,它会打开。但是我不能调用数据库方法。同样的操作在webui层可以无缝调用。 Startup.cs

应用设置

你能帮忙吗?

失败:

    fail: Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware[1]
      An unhandled exception has occurred while executing the request.
System.NullReferenceException: Object reference not set to an instance of an object.
   at zfc.webapi.Controllers.zfc.GetReferrer() in C:\Users\mderv\Desktop\zfc\zfc.webapi\Controllers\zfc.cs:line 26
   at lambda_method(Closure , Object , Object[] )
   at Microsoft.Extensions.Internal.ObjectMethodExecutor.Execute(Object target, Object[] parameters)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ActionMethodExecutor.SyncActionResultExecutor.Execute(IActionResultTypeMapper mapper, ObjectMethodExecutor executor, Object controller, Object[] arguments)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.InvokeActionMethodAsync()
   at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.InvokeNextActionFilterAsync()
--- End of stack trace from previous location where exception was thrown ---
   at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Rethrow(ActionExecutedContextSealed context)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.InvokeInnerFilterAsync()
--- End of stack trace from previous location where exception was thrown ---
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeFilterPipelineAsync>g__Awaited|19_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeAsync>g__Awaited|17_0(ResourceInvoker invoker, Task task, IDisposable scope)
   at Microsoft.AspNetCore.Routing.EndpointMiddleware.<Invoke>g__AwaitRequestTask|6_0(Endpoint endpoint, Task requestTask, ILogger logger)
   at Microsoft.AspNetCore.Authorization.AuthorizationMiddleware.Invoke(HttpContext context)
   at Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.Invoke(HttpContext context)
   at Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)

Csproj

存储库

您正在使用依赖注入来使用您的 chatRepository 并且注入配置不当,

services.AddScoped<InterfaceOfMyReposiory,ImplementationOfMyRepository>();

所以让我们假设您的 ChatRepository 是:

public class ChatRepository :IChatRepository {
 //some special impelementation
}

你有这样的界面:

public interface IChatRepository {

// some great methods definitions
}

所以在你的 startup.cs class 你应该这样配置它:

services.AddScoped<IChatRepository ,ChatRepository>();

您可以查看更多详情here

在您的情况下,这应该可以解决 null 异常: ChatRepository : interface

EfChatRepositoryEfGenericRepository:实施

services.AddScoped<ChatRepository ,EfChatRepository>(); 

EfChatRepository继承了EfGenericRepository

的实现

根据您到目前为止的屏幕截图和错误,我假设您没有在 startup.cs 文件中正确注册服务。

我在这里为您添加了一个完整的示例,您可以如何使用您的体系结构访问数据库中的数据。

摘要:

public interface IChatRepository
{
    object GetDataFromDatabase();
}

具体的:

public class ChatRepository : IChatRepository
{
    private readonly AppDbContext _dbContext;

    public ChatRepository(AppDbContext dbContext)
    {
        this._dbContext = dbContext;
    }

    public object GetDataFromDatabase()
    {
        var dataFromDatabase = _dbContext.PrinterJobs.ToList();
        return dataFromDatabase;
    }
}

注意:我在这里注入了一个dbContextclass实例来访问数据库对象。 dbContextIChatRepositoryChatRepository 需要在 startup.cs 文件中注册。

启动:

public void ConfigureServices(IServiceCollection services)
{
    services.AddCors(options => options.AddPolicy("AllowAll", p => p.AllowAnyOrigin()
                                                                   .AllowAnyMethod()
                                                                    .AllowAnyHeader()));
         
    services.AddScoped<IChatRepository, ChatRepository>();
    services.AddDbContext<AppDbContext>(options =>
                 options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
           
    services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);

    services.AddMvc().AddRazorPagesOptions(options =>
            {
                options.Conventions.ConfigureFilter(new IgnoreAntiforgeryTokenAttribute());
            });
}

AppDbContext:

public class AppDbContext: DbContext
{
    public AppDbContext(DbContextOptions<AppDbContext> options) : base(options)
    {
    }
       
    public DbSet<PrinterJob> PrinterJobs { get; set; }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<PrinterJob>().ToTable("PrintJob");
    }

    internal object Query<T>(string v, string name, int employeeId)
    {
        throw new NotImplementedException();
    }
}

PrinterJob 示例模型 class:

public class PrinterJob
{
        [Key]
        public int PrinterId { get; set; }
        public string PrinterName { get; set; }
        public int PrintedBy { get; set; }
        public int TotalPrint { get; set; }
}

数据库脚本:

CREATE TABLE PrintJob 
(
    [PrinterId] [int] PRIMARY KEY  IDENTITY(1,1)  NOT NULL,
    [PrinterName] [nvarchar](100) NULL,
    [PrintedBy] [int] NULL,
    [TotalPrint] [int] NULL,
 )

注意: 从 about 脚本创建 table 后,将一些示例数据添加到 table。

appsettings.json:

"ConnectionStrings": {
    "DefaultConnection": "Server=YourServerName;Database=YourDatabaseName;Trusted_Connection=True;MultipleActiveResultSets=true"
}

注意:确保您引用的是正确的数据库以相应地访问您的数据。

控制器:

    [Route("api/ZfcData")]
    public class ZfcDataController : Controller
    {
        private readonly IChatRepository _chatRepository;

        public ZfcDataController(IChatRepository chatRepository)
        {
            this._chatRepository = chatRepository;
        }
      
        [HttpGet("[action]")]
        [Route("GetDataFromDatabase")]
        [ActionName("GetDataFromDatabase")]
        public object GetDataFromDatabase()
        {
            var callRepository = _chatRepository.GetDataFromDatabase();
            return Ok(callRepository);
        }
        
    }

输出:

希望它能指导您完成并帮助您解决问题和实施。