簡體   English   中英

在 ASP.NET Core 中使用 datetime 返回 http 500 錯誤

[英]Using datetime in ASP.NET Core returns http 500 error

    DateTime startTime = DateTime.Now;
    DateTime endTime = DateTime.Now;

    public ActionResult Session()
    {
        if (TempData["time"] == null)
        {
            startTime = DateTime.Now;
            endTime = startTime.AddSeconds(120);
            var timeRem = endTime - startTime;
            var nn = timeRem.TotalSeconds;
            TempData["time"] = nn;
        }
        // else
        // {
        //    DateTime refreshTime = DateTime.Now;
        //    var timeRem = endTime - refreshTime;
        //    var nn = timeRem.TotalSeconds;
        //    TempData["time"] = nn;
        // }

        return View();
    }

啟動代碼

namespace OnlineExam
{
    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.AddControllersWithViews();

            services.AddEntityFrameworkSqlServer();
            services.AddIdentity<OnlineExam.Models.UserAccountModel.ApplicationUser, IdentityRole>(options =>
            {
                options.User.AllowedUserNameCharacters = default;
                options.User.RequireUniqueEmail = false;
            })
                    .AddEntityFrameworkStores<Models.UserAccountModel.OnlineExamDBContext>();

            //services.AddMvc();
            services.AddMvc(options =>
            {
                var policy = new AuthorizationPolicyBuilder()
                           .RequireAuthenticatedUser()
                           .Build();
                options.Filters.Add(new AuthorizeFilter(policy));
            });
            services.AddDbContext<OnlineExamDBContext>(options => options.UseSqlServer(Configuration.GetConnectionString("LoginConnection")));
            services.AddDbContext<OnlineExam.Models.AdminQuestionModel.OnlineExamDBContext>(options => options.UseSqlServer(Configuration.GetConnectionString("LoginConnection")));
            services.AddDbContext<CandidateLoginDBContext>(options => options.UseSqlServer(Configuration.GetConnectionString("LoginConnection")));
            services.AddDbContext<OnlineExam.Models.CandidateExam.CandidateExamDBContext>(options => options.UseSqlServer(Configuration.GetConnectionString("LoginConnection")));
            services.AddScoped<OnlineExam.Models.UserAccountModel.OnlineExamDBContext>();
            //services.AddScoped<OnlineExam.Controllers.AdminQuestionController>();

            //services.AddSession(x => x.IdleTimeout = TimeSpan.FromMinutes(1));
        }

        // 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.UseSession(); //for sessions
            app.UseHttpsRedirection();
            app.UseStaticFiles();

            app.UseRouting();

            app.UseAuthentication();

            app.UseAuthorization();

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

我可以知道我犯了什么錯誤嗎? 該代碼返回 http 500 錯誤。 我在視圖中有一個簡單的文本。 它仍然顯示 http 500 錯誤。 如果我刪除日期時間代碼,那么錯誤就會消失

終於我想通了!!

Tempdata 直接不支持存儲復雜的數據類型,如 DateTime、var 等。存儲這些復雜的數據類型需要在傳遞到視圖之前進行序列化。

在我的情況下,我將數據類型轉換或轉換為 int。 從而解決了這個問題。 這里的代碼

DateTime startTime = DateTime.Now;
 DateTime endTime = DateTime.Now;

    public ActionResult Session()
    {
        if (TempData["time"] == null)
        {
            startTime = DateTime.Now;
            endTime = startTime.AddSeconds(120);
            var timeRem = endTime - startTime;
            int nn = (int)timeRem.TotalSeconds; //correction line
            TempData["time"] = nn;
        }
        // else
        // {
        //    DateTime refreshTime = DateTime.Now;
        //    var timeRem = endTime - refreshTime;
        //    var nn = timeRem.TotalSeconds;
        //    TempData["time"] = nn;
        // }

        return View();
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM