将 ASP.NET MVC HttpContext 发送到 Web Api HttpContext

卡洛斯基

我正在尝试上传一个文件,我想将当前的 MVC HttpContext.Current.Request.Files 传递给 Web API。

我试图将HttpFileCollectionBaseas 参数传递给 API,但它始终为空。控制器

public object UploadAttachment(string param1, int param2, HttpFileCollectionBase files)
{
   string _url = _restUrl + param1+ "/Folders/" + param2+ "/UploadAttachment";
   HttpResponseMessage _response = SendJsonRequest(_url, HttpMethod.Post, files);
   var ret = DeserializeResponse(_response);
   return ret;
}

API代码

[HttpPost]
[Route("Archives/{param1}/Folders/{param2}/UploadAttachment")]      
public IHttpActionResult UploadAttachment([FromUri]string param1, [FromUri]int param2, [FromBody] HttpFileCollectionBase files)

查看代码

using (Ajax.BeginForm("UploadAttachment", null, new { param1 = Model.Param1 }, new AjaxOptions { HttpMethod = "POST", OnSuccess = "uploadAttachmentSuccess" }, new { id = "uploadAttachment", enctype = "multipart/form-data" }))
                    {
                    <div class="row">
                        <div class="col-xs-10">
                            <div class="input-group">
                                <label class="input-group-btn" title="">
                                    <span class="btn btn-primary">
                                        <input type="file" name="file_upload" id="file_upload" style="display: none;" multiple />
                                        Browse
                                    </span>
                                </label>
                                <input type="text" id="file_upload_name" class="form-control" readonly>
                            </div>
                        </div>
                        <div class="col-xs-2">
                            <button type="submit" class="btn btn-success" data-toggle="tooltip" id="btn-submit-upload" title="" disabled>
                                Upload
                            </button>
                        </div>
                    </div>
                    <div class="row">
                        <div class="col-xs-12" id="warning-format">
                        </div>
                    </div>
                    }

SendJsonRequest 实现

            protected virtual HttpResponseMessage SendJsonRequest(string url, HttpMethod method, object objectToSerialize = null, bool tryToRefreshToken = true)
    {
        ...
        HttpRequestMessage _request = new HttpRequestMessage(method, _uri);
        if (objectToSerialize != null)
        {
            string _serializedJSONObject = JsonConvert.SerializeObject(objectToSerialize);
            _request.Content = new StringContent(_serializedJSONObject);
            _request.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
        }...
穆克什·莫德瓦迪亚

我创建了一个示例,用于将文件从 MVC 控制器上传到 Web Api 控制器,并且运行良好

MVC控制器:

    [ActionName("FileUpload")]
    [HttpPost]
    public ActionResult FileUpload_Post()
    {
        if (Request.Files.Count > 0)
        {
            var file = Request.Files[0];

            using (HttpClient client = new HttpClient())
            {
                using (var content = new MultipartFormDataContent())
                {
                    byte[] fileBytes = new byte[file.InputStream.Length + 1];                     file.InputStream.Read(fileBytes, 0, fileBytes.Length);
                    var fileContent = new ByteArrayContent(fileBytes);
                    fileContent.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment") { FileName = file.FileName };
                    content.Add(fileContent);
                    var result = client.PostAsync(requestUri, content).Result;
                    if (result.StatusCode == System.Net.HttpStatusCode.Created)
                    {
                        ViewBag.Message= "Created";
                    }
                    else
                    {
                        ViewBag.Message= "Failed";
                    }
                }
            }
        }
        return View();
    }

Web API 控制器:

    [HttpPost]
    public HttpResponseMessage Upload()
    {
        if(!Request.Content.IsMimeMultipartContent())
        {
            throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
        }
        if (System.Web.HttpContext.Current.Request.Files.Count > 0)
        {
            var file = System.Web.HttpContext.Current.Request.Files[0];
            ....
            // save the file
            ....
            return new HttpResponseMessage(HttpStatusCode.Created);
        }
        else
        {
            return new HttpResponseMessage(HttpStatusCode.BadRequest);
        }
    }

有关在 Web Api 中保存文件的更多信息,请参阅Web API:文件上传

希望有帮助!

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

将修改后的表发送到ASP.NET MVC中的控制器?

如何从HttpContext获取ASP.NET Core MVC筛选器

System.Web.HttpContext.Current.get在ASP.NET MVC控制器中返回null

如何通过ActionLink将项目发送到ASP.NET MVC控制器?

ASP.NET Web API将复杂对象发送到前端

如何将多部分/表单数据发送到ASP.NET Core Web API?

将数字数组从JS发送到asp.net MVC操作

ASP.NET Core 2.1 MVC使用XMLHttpRequest将数据从JavaScript发送到Action方法

ASP.NET MVC过滤器中的filterContext.RequestContext.HttpContext和filterContext.HttpContext之间的区别?

如何将表单的数据发送到用Angular中的[FromForm]装饰的ASP.NET Core Web API操作?

将List <T>作为可选参数发送到ASP.NET Core Web Api中的帖子正文中

如何将2个对象发送到我的API(ASP.NET)?

AngularJS $ http.post()将null发送到ASP.NET Web API控制器方法

在ASP.NET 5中为Web API控制器模拟HttpContext

ASP.NET Web Api中HttpContext.Current.Items的替代方法

如何将JS对象的集合发送到ASP.NET API服务?

无法将多个文件从JQuery AJAX发送到ASP.NET MVC

如何使用angular将文件发送到asp.net Web API?

将Javascript数组发送到控制器ASP.NET MVC

ASP.NET Web API HttpContext 响应在 IOwinContext 响应之前发回

ASP.NET MVC 将 List<Foo> 集合从我的视图发送到控制器

将 JSON 字符串发送到 ASP.NET Core MVC 控制器

ASP.Net Web API HttpClient 不会将数据发送到目标 Web API Uri

如何使用 fetch 将 FormData 从 javascript 发送到 ASP.NET Core 2.1 Web API

将 ViewModel 发送到 API ASP.net Core 2

将值从 Windows 窗体应用程序发送到 Asp.Net Core Api

无法使用 Jquery 将数据从视图发送到控制器 Asp.net MVC

将 JSON 从视图发送到控制器 ASP.NET MVC 给出空值

将图像从 ASP.NET Web API 发送到 Angular 客户端