Send ASP.NET MVC HttpContext to Web Api HttpContext

霸气de小男生 提交于 2021-02-07 04:31:25

问题


I'm trying to upload a file and I'd like to pass the current MVC HttpContext.Current.Request.Files to a Web API.

I tried to pass the HttpFileCollectionBase as parameter to pass it to the API but it's always 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:

[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

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

回答1:


I have created a sample for uploading files from MVC controller to Web Api controller, and it's working perfectly

MVC controller :

    [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 :

    [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

Hope that helps!



来源:https://stackoverflow.com/questions/43207175/send-asp-net-mvc-httpcontext-to-web-api-httpcontext

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!