从WebAPI

时间:2017-02-08 15:11:03

标签: c# asp.net-mvc asp.net-mvc-4

这里提出了类似的问题: getting error while download the file in mvc2 但有一个答案并没有解决我的问题,我怀疑它解决了另一个人的问题......

这是我的问题: 我试图通过WebAPI公开pdf,xlsx,tif或任何类型的文档,这是我目前在API上的代码:

public HttpResponseMessage Download(string documentId, string contactId)
    {
        var path = DocumentSource + "\\";
        var document = DocumentDomain.GetDocument(new Guid(contactId), new Guid(documentId));

        if (ReferenceEquals(document, null) && ReferenceEquals(document.FileName, null))
        {
            return new HttpResponseMessage(HttpStatusCode.NotFound);
        }
        else
        {

            try
            {
                MemoryStream responseStream = new MemoryStream();
                Stream fileStream = new FileStream(Path.Combine(path,
                document.PortfolioId == null ? "" : document.PortfolioId.ToString(), document.FileName), FileMode.Open);
                bool fullContent = true;
                if (this.Request.Headers.Range != null)
                {
                    fullContent = false;

                    RangeItemHeaderValue range = this.Request.Headers.Range.Ranges.First();


                    // From specified, so seek to the requested position.
                    if (range.From != null)
                    {
                        fileStream.Seek(range.From.Value, SeekOrigin.Begin);

                        // In this case, actually the complete file will be returned.
                        if (range.From == 0 && (range.To == null || range.To >= fileStream.Length))
                        {
                            fileStream.CopyTo(responseStream);
                            fullContent = true;
                        }
                    }
                    if (range.To != null)
                    {
                        // 10-20, return the range.
                        if (range.From != null)
                        {
                            long? rangeLength = range.To - range.From;
                            int length = (int)Math.Min(rangeLength.Value, fileStream.Length - range.From.Value);
                            byte[] buffer = new byte[length];
                            fileStream.Read(buffer, 0, length);
                            responseStream.Write(buffer, 0, length);
                        }
                        // -20, return the bytes from beginning to the specified value.
                        else
                        {
                            int length = (int)Math.Min(range.To.Value, fileStream.Length);
                            byte[] buffer = new byte[length];
                            fileStream.Read(buffer, 0, length);
                            responseStream.Write(buffer, 0, length);
                        }
                    }
                    // No Range.To
                    else
                    {
                        // 10-, return from the specified value to the end of file.
                        if (range.From != null)
                        {
                            if (range.From < fileStream.Length)
                            {
                                int length = (int)(fileStream.Length - range.From.Value);
                                byte[] buffer = new byte[length];
                                fileStream.Read(buffer, 0, length);
                                responseStream.Write(buffer, 0, length);
                            }
                        }
                    }
                }
                // No Range header. Return the complete file.
                else
                {
                    fileStream.CopyTo(responseStream);
                }
                fileStream.Close();
                responseStream.Position = 0;

                HttpResponseMessage response = new HttpResponseMessage();
                response.StatusCode = fullContent ? HttpStatusCode.OK : HttpStatusCode.PartialContent;
                response.Content = new StreamContent(responseStream);
                return response;
            }
            catch (IOException)
            {
                throw new HttpResponseException( HttpStatusCode.InternalServerError);
            }
        }
    }

然后我有一个单独的MVC应用程序,我在控制器中有以下代码,它试图下载指定的文件:

public ActionResult DownloadDocument(string documentId, string documentName)
    {
        var currentMember = Members.GetCurrentMember();
        if (currentMember != null)
        {
            var contactId = currentMember.GetProperty("contactID").Value.ToString();
            try
            {
                HttpWebRequest req = (HttpWebRequest)WebRequest.Create(ConfigurationManager.AppSettings["APIBaseUrl"] + "/api/document/downloadExcel?documentId=" + documentId + "&contactId=" + contactId);
                //req.Method = "GET";
                var response = (HttpWebResponse)req.GetResponse();

                byte[] data;
                using (Stream s = response.GetResponseStream())
                {
                    data = StreamToByteArray(s);                        
                }


                var mimeType = System.Web.MimeMapping.GetMimeMapping(documentName);
                Response.AppendHeader("Content-Disposition", "inline; filename=" + documentName);

                return File(data, mimeType); 
            }
            catch (Exception ex)
            {
                return Json(new { Message = ex.ToString() });
            }
        }

        return null;
    }

以下是我得到的错误,我很肯定它与建议的JsonRequestBehaviour无关,因为我没有从API返回json:

  

此请求已被阻止,因为敏感信息可能是
  当在GET请求中使用它时向第三方网站公开。   要允许GET请求,请将JsonRequestBehavior设置为AllowGet。

     

堆栈追踪:

[InvalidOperationException: This request has been blocked because sensitive information could be disclosed to third party web sites when
     

这用于GET请求。要允许GET请求,请设置   JsonRequestBehavior to AllowGet。]   System.Web.Mvc.JsonResult.ExecuteResult(ControllerContext context)   +292 System.Web.Mvc.ControllerActionInvoker.InvokeActionResult(ControllerContext   controllerContext,ActionResult actionResult)+39
  System.Web.Mvc.ControllerActionInvoker.InvokeActionResultFilterRecursive(IList的1 filters, Int32 filterIndex, ResultExecutingContext preContext, ControllerContext controllerContext, ActionResult actionResult) +116
System.Web.Mvc.ControllerActionInvoker.InvokeActionResultFilterRecursive(IList
1   filters,Int32 filterIndex,ResultExecutingContext preContext,   ControllerContext controllerContext,ActionResult actionResult)+529
  System.Web.Mvc.ControllerActionInvoker.InvokeActionResultFilterRecursive(IList的1 filters, Int32 filterIndex, ResultExecutingContext preContext, ControllerContext controllerContext, ActionResult actionResult) +529
System.Web.Mvc.ControllerActionInvoker.InvokeActionResultFilterRecursive(IList
1   filters,Int32 filterIndex,ResultExecutingContext preContext,   ControllerContext controllerContext,ActionResult actionResult)+529
  System.Web.Mvc.ControllerActionInvoker.InvokeActionResultFilterRecursive(IList 1 filters, Int32 filterIndex, ResultExecutingContext preContext, ControllerContext controllerContext, ActionResult actionResult) +529
System.Web.Mvc.ControllerActionInvoker.InvokeActionResultWithFilters(ControllerContext controllerContext, IList
1个过滤器,ActionResult actionResult)+106
  System.Web.Mvc.Async&LT;&GT; c__DisplayClass2b.b__1c()   +321 System.Web.Mvc.Async。&lt;&gt; c__DisplayClass21.b__1e(IAsyncResult)   asyncResult)+185
  System.Web.Mvc.Async.WrappedAsyncResult 1.CallEndDelegate(IAsyncResult asyncResult) +42
System.Web.Mvc.Async.WrappedAsyncResultBase
1.End()+133
  System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult,   对象标签)+56
  System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeAction(IAsyncResult的   asyncResult)+40
  System.Web.Mvc.Controller.b__1d(IAsyncResult的   asyncResult,ExecuteCoreState innerState)+34
  System.Web.Mvc.Async.WrappedAsyncVoid 1.CallEndDelegate(IAsyncResult asyncResult) +70
System.Web.Mvc.Async.WrappedAsyncResultBase
1.End()+133
  System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult,   对象标签)+56
  System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult,   对象标签)+37
  System.Web.Mvc.Controller.EndExecuteCore(IAsyncResult asyncResult)+44   System.Web.Mvc.Controller.b__15(IAsyncResult的   asyncResult,控制器控制器)+39
  System.Web.Mvc.Async.WrappedAsyncVoid 1.CallEndDelegate(IAsyncResult asyncResult) +62
System.Web.Mvc.Async.WrappedAsyncResultBase
1.End()+133
  System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult,   对象标签)+56
  System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult,   对象标签)+37 System.Web.Mvc.Controller.EndExecute(IAsyncResult   asyncResult)+39
  System.Web.Mvc.Controller.System.Web.Mvc.Async.IAsyncController.EndExecute(IAsyncResult的   asyncResult)+39
  System.Web.Mvc.MvcHandler.b__5(IAsyncResult的   asyncResult,ProcessRequestState innerState)+39
  System.Web.Mvc.Async.WrappedAsyncVoid 1.CallEndDelegate(IAsyncResult asyncResult) +70
System.Web.Mvc.Async.WrappedAsyncResultBase
1.End()+133
  System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult,   对象标签)+56
  System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult,   对象标签)+37
  System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult)   +40 System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult)   结果)+38
  System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()   +9765121 System.Web.HttpApplication.ExecuteStep(IExecutionStep step,Boolean&amp; completedSynchronously)+155

1 个答案:

答案 0 :(得分:0)

您正在id行动中在MVC应用程序的try catch块的catch部分返回Json。这可能就是你收到错误的原因。

尝试

DownloadDocument