简体   繁体   中英

Why am I getting a strange exception when I try to de-serialize a FormFile object in .NET Core?

I have an MVC .NET Core web application, and in one controller method I am serializing a FormFile object named "file", like so:

var serializedFile = JsonConvert.SerializeObject(file, new JsonSerializerSettings
                    {
                        TypeNameHandling = TypeNameHandling.Auto,
                        NullValueHandling = NullValueHandling.Ignore,
                    });

Then in the same controller method, I am storing this serialized variable in TempData, like so:

TempData["myFile"] = serializedFile ;

And then in another controller method, I am attempting to deserialize this object, like so:

    var deserializedFile = JsonConvert.DeserializeObject<FormFile>(TempData["myFile"].ToString(),
        new JsonSerializerSettings
        {
            TypeNameHandling = TypeNameHandling.Auto,
            NullValueHandling = NullValueHandling.Ignore,
        });

But when I do, I am getting this exception thrown: Newtonsoft.Json.JsonSerializationException: 'Error setting value to 'ContentDisposition' on 'Microsoft.AspNetCore.Http.FormFile'.' Inner Exception NullReferenceException: Object reference not set to an instance of an object.

I have tried for a long and frustrating time, but I have not been able to figure out why it's happening. Any help would be appreciated? Thanks!

You have to fix temp data names

TempData["myFile"] = serializedFile ;
// and 
TempData["theFile"].ToString(),

you should select only one - "myFile" or "theFile"

and to prevent exceptions it is better to use this syntax

if (TempData.ContainsKey("myFile"))
{
.....
}

TempData by default has very small capacity, since it is kept as cookies.Its size is less than 4kb. One of the reasons the you can get data could be this. You have to configure session to allow to keep more data.

To do this you can folow this https://docs.microsoft.com/en-us/aspnet/core/fundamentals/app-state?view=aspnetcore-3.1&WT.mc_id=DT-MVP-5003235#configure-the-tempdata-provider

Another reason is that TempData clears after first reading. So if you use it before, it can be null too. To keep data you have to read using Keep or Peak keywords. And it keeps data not forever, but only between 2 requests. After this data dissapears too.

Alternatively you can use Session instead of TempData, but it will drop scalability of your applications, because it will have to create a Session object for every connected user, and each object takes some server resources memory or hard drive.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM