HttpResponseMessage DownloadFile有效,但返回null吗?

时间:2019-12-15 11:45:52

标签: c# api downloadfile httpresponsemessage

我正在尝试从服务器下载文件,一切正常,我更正了文件路径,并且此代码返回null,并且不显示任何错误代码。

我的错误在哪里?

        [HttpPost]
    public HttpResponseMessage GetFile(DownloadInput input)
    {
        //Create HTTP Response.
        HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.OK);
        var fileName = input.DosyaAdi;
        //Set the File Path.
        //string filePath = HttpContext.Current.Server.MapPath("~/Uploads/")+ input.SorunID + "\\" + fileName;
        string filePath = "C:\\Uploads\\177738\\" + fileName;

        //Check whether File exists.
        if (!File.Exists(filePath))
        {
            //Throw 404 (Not Found) exception if File not found.
            response.StatusCode = HttpStatusCode.NotFound;
            response.ReasonPhrase = string.Format("File not found: {0} .", fileName);
            throw new HttpResponseException(response);
        }

        //Read the File into a Byte Array.
        byte[] bytes = File.ReadAllBytes(filePath);

        //Set the Response Content.
        response.Content = new ByteArrayContent(bytes);

        //Set the Response Content Length.
        response.Content.Headers.ContentLength = bytes.LongLength;

        //Set the Content Disposition Header Value and FileName.
        response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment");
        response.Content.Headers.ContentDisposition.FileName = fileName;

        //Set the File Content Type.
        response.Content.Headers.ContentType = new MediaTypeHeaderValue(MimeMapping.GetMimeMapping(fileName));
        return response;
    }

0 个答案:

没有答案