简体   繁体   English

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

[英]Send ASP.NET MVC HttpContext to Web Api HttpContext

I'm trying to upload a file and I'd like to pass the current MVC HttpContext.Current.Request.Files to a Web API. 我正在尝试上传文件,我想将当前的MVC HttpContext.Current.Request.Files传递到Web API。

I tried to pass the HttpFileCollectionBase as parameter to pass it to the API but it's always null. 我尝试将HttpFileCollectionBase作为参数传递给API,但始终为null。 Controller 调节器

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 code : API代码

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

View Code 查看代码

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 Implementation 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");
        }...

I have created a sample for uploading files from MVC controller to Web Api controller, and it's working perfectly 我创建了一个示例,用于将文件从MVC控制器上传到Web Api控制器,并且运行良好

MVC controller : 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 controller : 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);
        }
    }

For more information on saving file in Web Api, refer Web API: File Upload 有关在Web Api中保存文件的更多信息,请参考Web API:文件上传

Hope that helps! 希望有帮助!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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