将ASP.NET MVC HttpContext发送到Web Api HttpContext [英] Send ASP.NET MVC HttpContext to Web Api HttpContext

查看:65
本文介绍了将ASP.NET MVC HttpContext发送到Web Api HttpContext的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试上传文件,并且希望将当前的MVC HttpContext.Current.Request.Files传递到Web API.

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

我尝试将 HttpFileCollectionBase 作为参数传递给API,但始终为null.控制器

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

[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控制器,并且运行良好

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

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控制器:

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

有关在Web Api中保存文件的更多信息,请参考

For more information on saving file in Web Api, refer Web API: File Upload

希望有帮助!

这篇关于将ASP.NET MVC HttpContext发送到Web Api HttpContext的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆