.Net Web Api — ArrayBuffer путается с другими вызовами API

У меня есть несколько функций контроллера веб-API, которые выглядят следующим образом.

[HttpGet]
    [Route("GetCycle")]
    public HttpResponseMessage GetCycle(string type) {
        try
        {
            Cycle oCycleClass = Data.GetCycle(type);
            return Request.CreateResponse(oCycleClass);

        }
        catch (Exception ex)
        {
            return Request.CreateErrorResponse(System.Net.HttpStatusCode.BadRequest, ex.Message);
        }

    }

Это еще один контроллер, который работает так, как ожидалось.

[HttpPost]
    [Route("GetDataDownload")]
    public HttpResponseMessage GetDataExport([FromBody]DataObject objectData)
    {
        try
        {
            byte[] excelData = Data.GetDataExport(objectData);

            String timeStamp = DateTime.Now.ToString("yyyy-MM-dd HH mm ss");

            HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK);
            response.Content = new ByteArrayContent(excelData);
            response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment");
            response.Content.Headers.ContentDisposition.FileName = "DataExport - " + focalData.User.ID + " - " + timeStamp + ".xlsx";

            return response;
        }
        catch (Exception ex)
        {
            return Request.CreateErrorResponse(System.Net.HttpStatusCode.BadRequest, ex.Message);
        }
    }

Ошибка возникает после того, как я запускаю любой другой контроллер после функции GetDataExport. Похоже, что HttpResponseMessage каким-то образом поврежден.

Например:

1. Выполнить GetCycle - Результат: Успешно

2. Выполнить GetDataExport - Результат: Успешно

3. Выполнить GetCycle - Результат: Ошибка


GetDataExport функция ниже

public static byte[] GetDataExport(DataObject dataObject)
    {
        DataTable view = Common.ConvertToDataTable<View>(dataObject.Views);
        string filter = Common.ConvertFiltersToSQLStatement(dataObject.Filters);

        DataSet ds;

        if (dataObject.DownloadWithFilters)
        {
            ds = InterfaceDataClass.GetEmployees(dataObject.CycleId, view, filter, 1, 0, true);
        }
        else
        {
            ds = InterfaceDataClass.GetEmployees(dataObject.CycleId, view, string.Empty, 1, 0, true);
        }

        using (ExcelPackage pck = new ExcelPackage())
        {
            //Create the worksheet
            ExcelWorksheet ws = pck.Workbook.Worksheets.Add("Employees");

            //Load the datatable into the sheet, starting from cell A1. Print the column names on row 1
            ws.Cells["A1"].LoadFromDataTable(ds.Tables[0], true);

            //Format the header column
            using (ExcelRange rng = ws.Cells["A1:BB1"])
            {
                rng.Style.Fill.PatternType = ExcelFillStyle.Solid;
                rng.Style.Fill.BackgroundColor.SetColor(Color.FromArgb(122, 122, 122));
                rng.Style.Font.Color.SetColor(Color.WhiteSmoke);
            }

            return pck.GetAsByteArray();
        }
    }

ExcelPackage происходит из библиотеки под названием EPPlus


person Oscar Rodriguez Arroyo    schedule 11.10.2017    source источник
comment
Зарегистрирована ли какая-либо ошибка?? Кроме того, убедитесь, что вы тщательно закрываете ресурсы.   -  person Ipsit Gaur    schedule 11.10.2017
comment
Как правильно закрыть ресурсы?   -  person Oscar Rodriguez Arroyo    schedule 11.10.2017
comment
Я предполагаю, что вы обращаетесь к какому-то файловому потоку, пожалуйста, закройте его в этом случае. Также, если вы можете поделиться кодом метода GetDataExport, это было бы полезно.   -  person Ipsit Gaur    schedule 11.10.2017
comment
Я не использую потоки.   -  person Oscar Rodriguez Arroyo    schedule 11.10.2017
comment
Пожалуйста, опубликуйте код метода GetDataExport для получения дополнительной помощи.   -  person Ipsit Gaur    schedule 11.10.2017
comment
Я только что добавил функцию GetDataExport.   -  person Oscar Rodriguez Arroyo    schedule 11.10.2017


Ответы (1)


В API вообще не было ошибок. Проблема заключалась в том, как вызывался и выполнялся API.

person Oscar Rodriguez Arroyo    schedule 13.12.2017