无法发布formdata正确

时间:2018-06-14 11:33:03

标签: c# post asp.net-web-api

当我使用以下表格并POST到我的api时,我可以提取隐藏的输入值



<form name="form1" method="post" enctype="multipart/form-data" action="api/upload">
    <div>
        <label for="caption">Image Caption</label>
        <input name="caption" type="text" />
    </div>
    <div>
        <input type="hidden" name="pFoo" value="foo"/>
        <input type="hidden" name="pName" value="Foo bar"/>

        <label for="fileInput">Image File</label>
        <input type="file" id="fileInput" name="fileInput"/>
    </div>
    <div>
        <input type="submit" value="Submit" />
    </div>
</form>
&#13;
&#13;
&#13;

使用此代码..

    public Task<HttpResponseMessage> PostFormData()
    {
        // Check if the request contains multipart/form-data.
        if (!Request.Content.IsMimeMultipartContent())
        {
            throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
        }

        HttpContext httpContext = HttpContext.Current;

        var authHeader = httpContext.Request.Headers["Authorization"];

        if (authHeader != null && authHeader.StartsWith("Basic"))
        {
            var encodedUsernamePassword = authHeader.Substring("Basic ".Length).Trim();
            var encoding = Encoding.GetEncoding("iso-8859-1");
            var usernamePassword = encoding.GetString(Convert.FromBase64String(encodedUsernamePassword));

            var seperatorIndex = usernamePassword.IndexOf(':');

            var username = usernamePassword.Substring(0, seperatorIndex);
            var password = usernamePassword.Substring(seperatorIndex + 1);
        }
        else
        {
            Log.Error("The authorization header is either empty or isn't Basic.");
        }


        var sourcePath = HttpContext.Current.Server.MapPath("~/App_Data/Temp/");
        var destPath = HttpContext.Current.Server.MapPath("~/App_Data/");
        string destFileName;
        var streamProvider = new MultipartFormDataStreamProvider(sourcePath);


        // Read the form data and return an async task.
        var task = Request.Content.ReadAsMultipartAsync(streamProvider).
            ContinueWith<HttpResponseMessage>(t =>
            {

                //var options = JsonConvert.DeserializeObject<Order>(streamProvider.FormData["options"]);
                var formStreamToRead = streamProvider.Contents.First(x => x.Headers.ContentDisposition.Name == "\"pFoo\"");
                var extractedParam = formStreamToRead.ReadAsStringAsync();
                var pFoo = extractedParam.Result;

                formStreamToRead = streamProvider.Contents.First(x => x.Headers.ContentDisposition.Name == "\"pName\"");
                extractedParam = formStreamToRead.ReadAsStringAsync();
                var pName = extractedParam.Result;

                if (t.IsFaulted || t.IsCanceled)
                {
                    Log.Error(t.Exception);
                    Request.CreateErrorResponse(HttpStatusCode.InternalServerError, t.Exception);
                }

                foreach (var fileData in streamProvider.FileData)
                {
                    var fileName = "";
                    if (string.IsNullOrEmpty(fileData.Headers.ContentDisposition.FileName))
                    {
                        fileName = Guid.NewGuid().ToString();
                    }
                    fileName = fileData.Headers.ContentDisposition.FileName;
                    if (fileName.StartsWith("\"") && fileName.EndsWith("\""))
                    {
                        fileName = fileName.Trim('"');
                    }
                    if (fileName.Contains(@"/") || fileName.Contains(@"\"))
                    {
                        fileName = Path.GetFileName(fileName);
                    }

                    destFileName = Path.GetDirectoryName(fileName) + Guid.NewGuid() + Path.GetExtension(fileName);

                    File.Move(fileData.LocalFileName, Path.Combine(destPath, destFileName));
                    Log.Info($"File:  {destFileName}");
                }

                return Request.CreateResponse(HttpStatusCode.OK);
            });

        return task;
    }

但是,如果我尝试从CodeBehind POST,如下所示我无法读取表单值pFoo和pName beacuse然后我得到一个&#34;序列不包含匹配元素&#34; &#34; streamProvider.Contents.First&#34;上的错误部分

        using (var client = new HttpClient())
        {
            using (var content = new MultipartFormDataContent())
            {
                var values = new[]
                {
                    new KeyValuePair<string, string>("pFoo", "Bar"),
                    new KeyValuePair<string, string>("pName", "Fo bar"),
                };

                foreach (var keyValuePair in values)
                {
                    content.Add(new StringContent(keyValuePair.Value), keyValuePair.Key);
                }

                var fileContent = new ByteArrayContent(System.IO.File.ReadAllBytes(@"D:\Temp\image.png"));
                fileContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data")
                {
                    Name = "attachment",
                    FileName = "Foo.png"
                };
                content.Add(fileContent);
                client.DefaultRequestHeaders.Add("Authorization", "Basic " + Convert.ToBase64String(Encoding.Default.GetBytes("usernamne" + ":" + "pass")));

                var requestUri = "http://localhost:63284/api/upload";
                var result = client.PostAsync(requestUri, content).Result;
            }

任何人都会看到我在这里做错了什么以及我需要修理什么?

0 个答案:

没有答案