我如何在ASP.NET MVC Core中使用临时数据 [英] how do i use temp data in asp.net mvc core

查看:72
本文介绍了我如何在ASP.NET MVC Core中使用临时数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要帮助以了解使用tempdata时会发生什么情况.如果我在视图中使用tempdata,如果两个用户同步转到该视图,那么tempdata会发生什么?我的意思是,数据是否正在丢失,或者这两个临时数据是否会不同并且可以正常运行.

i need help for understand when use tempdata what happen. if i use tempdata in view , if two users synchronous go to the view , what happen for tempdata? I mean, whether the data is dropping, or whether the two tempdata will be different and will function properly.

推荐答案

首先,TempData基于会话,因此每个用户都有自己的会话,这就是为什么两个用户在同一时间使用同一页面没有任何问题的原因时间.

First of all the TempData is based on Sessions so every user has it's own session that's why it doesn't have any problem if two user use same page at a same time.

这是一个示例代码,您如何实现您必须将会话中间件添加到ASP.NET Core管道中.否则,它将始终为null.您不会收到任何错误!

Here is a sample code how you can implement you have to add a Session Middleware to the ASP.NET Core Pipeline. Otherwise it always will be null. You will not get any error!

services.AddSession(); // Add in 'Startup.cs' file 'ConfigureServices' method

您还需要一个TempData提供程序.

You also need a TempData Provider.

services.AddSingleton<ITempDataProvider, CookieTempDataProvider>(); // Add in 'Startup.cs' file 'ConfigureServices' method

这是一个cookie提供程序,这意味着所有TempData内容都将放入请求A的cookie中,并在请求B中再次读取.

Here it is a cookie provider which means all TempData stuff will be put into a cookie from request A and will be read again in request B.

现在您还必须使用会话注册:

Now you also have to use the Session registration:

app.UseSession(); // Add in 'Startup.cs' file 'Configure' method

最后,您的 startup.cs 看起来像这样

Finally you your startup.cs look like this

来源

public void ConfigureServices(IServiceCollection services)
{
    // Add framework services.

    services.AddMvc();

    services.AddSingleton<ITempDataProvider, CookieTempDataProvider>();
    services.AddSession();

    // Adds a default in-memory implementation of IDistributedCache.
    services.AddDistributedMemoryCache();
}

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
    loggerFactory.AddConsole(Configuration.GetSection("Logging"));
    loggerFactory.AddDebug();

    app.UseDeveloperExceptionPage();

    app.UseStaticFiles();

    app.UseSession();

    app.UseMvc(routes =>
    {
        routes.MapRoute(
            name: "default",
            template: "{controller=Home}/{action=Index}/{id?}");
    });
}

现在,您可以使用TempData将数据从一个动作传递到另一个动作.

Now you can use the TempData to pass data from one action to another.

public class TempDataDemoController : Controller
{
    public IActionResult RequestA()
    {
        ViewData["MyKey"] = "Hello TempData!";

        return RedirectToAction("RequestB");
    }

    public IActionResult RequestB()
    {
        return Content(ViewData["MyKey"] as string);
    }
}

这篇关于我如何在ASP.NET MVC Core中使用临时数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆