skip to Main Content

I am using TempData for temp storage of a list item.
I have used below code in program.cs

builder.Services.AddSingleton<ITempDataProvider, CookieTempDataProvider>();
builder.Services.AddSession();

//Other middleware

app.UseSession();

On a get request i have created a view model and stored the data from viewmodel into Tempdata as given below

 TempData["vMClient"] = JsonConvert.SerializeObject(vMClient);
 return View(vMClient);

Now whenever i am using Tempdata.Peek method my browser is throwing error code 431

View Page Code.

@model VMClient
@{
    var a = @TempData.Peek("vMClient");    
}

Error Link Image

Kindly help me to resolve this issue.

2

Answers


  1. Seems like the HTTP Error 431 is caused by passing the vMClient parameter to the view: it exceeded header size. And you don’t need to do that, because this data is already passing by the TempData. What you need is to use DeserializeObject().

    Try the following. In the action method:

     TempData["vMClient"] = JsonConvert.SerializeObject(vMClient);
     return View();
    

    In the view:

    @using Newtonsoft.Json
    @model VMClient
    @{
        var data = JsonConvert.DeserializeObject<VMClient>(TempData.Peek("VMClient").ToString());      
    }
    
    Login or Signup to reply.
  2. You can use HTTP cookies or session state as storage mechanism for TempData. The cookie-based TempData provider is the default. Session state can handle larger amounts of data compared to cookies state.

    The HTTP 431 status code indicates that the server is unwilling to process the request because its header fields are too large. This usually happens when there are too many cookies or large cookies being sent in the request.

    Based on the following example from docs you can enable the session-based TempData provider, by calling AddSessionStateTempDataProvider extension method.

    builder.Services.AddRazorPages()
                        .AddSessionStateTempDataProvider();
    //or
    builder.Services.AddControllersWithViews()
                        .AddSessionStateTempDataProvider();
    
    builder.Services.AddSession();
    
    var app = builder.Build();
    
    if (!app.Environment.IsDevelopment())
    {
        app.UseExceptionHandler("/Error");
        app.UseHsts();
    }
    
    app.UseHttpsRedirection();
    app.UseStaticFiles();
    
    app.UseRouting();
    
    app.UseAuthorization();
    
    app.UseSession();
    
    app.MapRazorPages();
    app.MapDefaultControllerRoute();
    
    app.Run();
    

    Another way, you can also store data in Session instead of TempData.Refer to: How to Set and get Session values

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search