webapi, how to read the file from a POST/PUT action with custom model binder

女生的网名这么多〃 提交于 2019-12-01 14:08:34

I didn't expect this, but it seems you have to include quotes when checking the name of the ContentDispositionHeader.

For file, instead of

var fileContent = provider.Contents.FirstOrDefault(n => n.Headers.ContentDisposition.Name.Equals("file"));

it must be

var fileContent = provider.Contents.FirstOrDefault(n => n.Headers.ContentDisposition.Name.Equals(@"""file"""));

For model it must be

var modelContent = provider.Contents.FirstOrDefault(n => n.Headers.ContentDisposition.Name.Equals(@"""model"""));

If you inspect the file in Visual Studio's Immediate Window via provider.Contents[0].Headers.ContentDisposition (might be index [1] for you) you see the output below.
Notice the difference in quotes between DispositionType: "form-data" and Name: "\"file\"", although both are of type String.

{form-data; name="file"; filename="upload.txt"}
    CreationDate: null
    DispositionType: "form-data"
    FileName: "\"upload.txt\""
    FileNameStar: null
    ModificationDate: null
    Name: "\"file\""
    Parameters: Count = 2
    ReadDate: null
    Size: null

I'm no React developer (yet), so I couldn't execute my Web APIcode via your React script, but I used this simple html form here below ... similar concept.
I see the same behaviour when posting via a tool like eg. Fiddler.

<html>
<head>
</head>
<body>
    <form method="post" enctype="multipart/form-data" action="http://url-to-your-webapi-controller-method-here">
        <input type="file" name="file" />
        <input type="text" name="model" />
        <input type="submit" />
    </form>
</body>
</html>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!