Home > Blockchain >  Trying to set ContentType for FormFile instance throws an exception
Trying to set ContentType for FormFile instance throws an exception

Time:08-18

I have the following simple method that creates a simple FormFile for testing.

    private static IFormFile CreateTemporaryFile(string fileName, string contentType)
    {

        byte[] bytes = Encoding.UTF8.GetBytes("Test content");

        var formFile = new FormFile(
            baseStream: new MemoryStream(bytes),
            baseStreamOffset: 0,
            length: bytes.Length,
            name: "Data",
            fileName: fileName);

        formFile.ContentType = contentType;
        return formFile;
    }

It keeps throws a NullReference exception at this line formFile.ContentType = contentType;. We have instance of the FormFile and ContentType is a public string property with getter and setter ? Am I missing anything ?

enter image description here

CodePudding user response:

Judging by the error and the fact that formFile clearly isn't null, it appears that ContentType itself is actually trying to access something that's null. From looking at the source code, that would appear to be the Headers property.

I believe you can initialize it like this:

private static IFormFile CreateTemporaryFile(string fileName, string contentType)
{

    byte[] bytes = Encoding.UTF8.GetBytes("Test content");

    var formFile = new FormFile(
        baseStream: new MemoryStream(bytes),
        baseStreamOffset: 0,
        length: bytes.Length,
        name: "Data",
        fileName: fileName) 
    {
        Headers = new HeaderDictionary()
    };

    formFile.ContentType = contentType;
    return formFile;
}
  • Related