ASP.NET Core 2 Controller的ActionMethod异步任务<fileresult>返回HttpresponseMessage

时间:2017-10-02 20:11:59

标签: c# asp.net-web-api asp.net-core-2.0 actionmethod fileresult

更新:正如我所说,我改变了我的行动方法,但没有成功。见截图

enter image description here

结果是一样的,无论如何:

enter image description here

简要总结一下我的问题: 一切都在dot net core 2.0中。我有一个WebAPI(单独的项目)和它的Controller(与SQL Server交谈)。我的客户端应用程序是一个ASP.NET核心MVC Web应用程序,其控制器的操作方法WOULD返回一个文件。在我的例子中是一个字节流。当我打开从运行我的客户端应用程序的浏览器下载的文件时,该文件就像一些以JSON样式格式包装的HttpResponseMessage。

API控制器

[Route("api/[controller]")]
public class GasDownloadController : Controller
{
    private readonly IGasesRepository _repository;

    public GasDownloadController(IGasesRepository repository)
    {
        _repository = repository;
    }

    [HttpGet]
    public HttpResponseMessage Export([FromQuery] Gas gas)
    {
        var item = _repository.GetGasesService(gas);

        byte[] outputBuffer = null;

        using (MemoryStream tempStream = new MemoryStream())
        {
            using (StreamWriter writer = new StreamWriter(tempStream))
            {
                FileWriter.WriteDataTable(item, writer, true);
            }
            outputBuffer = tempStream.ToArray();
        }
        HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK);
        result.Content = new ByteArrayContent(outputBuffer);
        result.Content.Headers.ContentType = new MediaTypeHeaderValue("text/csv");
        result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment") { FileName = $"ENVSdata.csv" };

        return result;
    }
}

助手类

public class FileWriter
{
    public static void WriteDataTable(DataTable sourceTable, TextWriter writer, bool includeHeaders)
    {
        if (includeHeaders)
        {
            writer.WriteLine("sep=,");
            IEnumerable<string> headerValues = sourceTable.Columns
                .OfType<DataColumn>()
                .Select(column => QuoteValue(column.ColumnName));
            writer.WriteLine(String.Join(",", headerValues));
        }

        IEnumerable<String> items = null;

        foreach (DataRow row in sourceTable.Rows)
        {
            items = row.ItemArray.Select(o => QuoteValue(o?.ToString() ?? String.Empty));
            writer.WriteLine(String.Join(",", items));
        }

        writer.Flush();
    }
    private static string QuoteValue(string value)
    {
        return String.Concat("\"",
            value.Replace("\"", "\"\""), "\"");
    }
}

MVC控制器

public class DownloadsController : Controller
{
    private IGasesRepository _repository;

    public DownloadsController(IGasesRepository repository)
    {
        _repository = repository;
    }

    [HttpGet]
    public ActionResult Index()
    {
        return View();
    }


    [HttpPost]
    public async Task<FileResult> GetFile(Gas inputGas)
    {
        var model = await _repository.GasDownloads(inputGas);
        return File(model, "text/csv", "data.csv");
    }
}

回购

public class GasesRepository : IGasesRepository
{
    public IEnumerable<Gas> Gases { get; set; }
    public byte[] CsvBytes { get; set; }

    private string BaseGasApiUrl = "http://localhost:XXXX";
    private string BaseDwnlApiUrl = "http://localhost:XXXX";

    public async Task<IEnumerable<Gas>> GasService(Gas gasCompound)
    {
       //code omitted for brewity
    }


    public async Task<byte[]> GasDownloads(Gas gasCompound)
    {
        UriBuilder builder = new UriBuilder(BaseDwnlApiUrl);
        builder.Query =
            $"XXXXX";

        using (var client = new HttpClient())
        {
            client.BaseAddress = new Uri(BaseDwnlApiUrl);
            client.DefaultRequestHeaders.Accept.Clear();

            try
            {
                HttpResponseMessage responseMessage = await client.GetAsync(builder.Uri);

                if (responseMessage.IsSuccessStatusCode)
                {
                    var apiResult = responseMessage.Content.ReadAsByteArrayAsync().Result;

                    CsvBytes = apiResult;
                }
                else
                    return null;
            }
            catch (HttpRequestException downloadRequestException)
            {
                throw new HttpRequestException(downloadRequestException.Message);
            }
            catch (ArgumentNullException argsNullException)
            {
                throw new ArgumentNullException(argsNullException.Message);
            }
        }
        return CsvBytes;
    }
}

结果

因此,当我打开浏览器下载的文件(f.ex:Excel)时,它是一个CSV文件,但它不是列和行以及其中的数据,而是一个

    {
  "version": {
    "major": 1,
    "minor": 1,
    "build": -1,
    "revision": -1,
    "majorRevision": -1,
    "minorRevision": -1
  },
  "content": {
    "headers": [
      {
        "key": "Content-Type",
        "value": [
          "text\/csv"
        ]
      },
      {
        "key": "Content-Disposition",
        "value": [
          "attachment; filename=data.csv"
        ]
      }
    ]
  },
  "statusCode": 200,
  "reasonPhrase": "OK",
  "headers": [

  ],
  "requestMessage": null,
  "isSuccessStatusCode": true
}

我已尝试过的内容:

如果我调试我可以看到我得到一个合法/有效的字节数组,但不知何故发生了一些魔法,或者它是如此明显和大,以至于我看不到树木的木头?

我尝试更改我的MVC控制器Action方法以返回许多可能类型的东西(IActionResult,IHttpResponse,FileContentResult等......)。

我在MVC 5中有相同的项目,没有问题,获得一个包含我的数据行和列的有效CSV文件。

非常感谢任何帮助!

0 个答案:

没有答案