Microsoft.AspNetCore.Mvc.Controller.TempData.get returned nu



在错误msg下方。

System.NullReferenceException: 'Object reference not set to an instance of an object.'
Microsoft.AspNetCore.Mvc.Controller.TempData.get returned null.

我在以下情况下收到此错误:

TempData["test"] = "test"; //this is for testing
TempData["test"] = someObj; //this is my aim, but I'm getting the same error

我不知道这是否重要,但我运行作为控制器的类的构造函数,然后通过反射 (method.Invoke(instanceConstructor, new object[] { colums }); )方法。在该方法的逻辑中,我尝试使用TempData

启动.cs

using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
public class Startup
{
    public Startup(IConfiguration configuration) => Configuration = configuration;
    public IConfiguration Configuration { get; }
    public void ConfigureServices(IServiceCollection services)
    {
        services.Configure<CookiePolicyOptions>(options =>
        {
            //options.CheckConsentNeeded = context => true; //this option my startup dosent know what it is. even if I copy/paste using's from github example, I just added those to the topic
            options.MinimumSameSitePolicy = SameSiteMode.None;
        });
        services.AddDistributedMemoryCache();
        services.AddMemoryCache();
        services.AddMvc() //.AddSessionStateTempDataProvider(); I tried with and without
        services.AddSession();
    }
    public void Configure(IApplicationBuilder app) //, IHostingEnvironment env
    {
        app.UseSession();
        app.UseAuthentication();
        app.UseMvcWithDefaultRoute();
        app.UseCookiePolicy();
      }
}

这很有趣,因为在另一个控制器中TempData工作正常。我检查了这些控制器的usings,这些usings是相同的。

TempData正在使用字符串类型的ProductController TempData["message"] = $"'{deletedProduct.Name}' - produkt został usunięty"; 它在没有app.UseCookiePolicy();的情况下也能工作ProductController

找到了一些主题,它将我重定向到 msdn,其中包含添加app.UseCookiePolicy();options to cokies的提示,但就像我说的它对我不起作用

我正在使用核心 2.0

请解释为什么TempData无法正常工作或帮助查找应用程序中的错误

我不知道这是否重要,但我运行的类的构造函数是一个 控制器,然后通过反射方法 (方法。Invoke(instanceConstructor, new object[] { colums });).在 该方法中的逻辑我正在尝试使用 TempData

它有问题! - 会话和临时数据通过反射在调用的方法上工作。

最新更新