none
Why exporting data to Excel cause a flush session problem? RRS feed

  • שאלה

  • Hi,

    I develop a web API with ASP.NET C# and angular 8.

    I try to export some data from Oracle into Excel file on server side and download it in client side.

    I did it before and it works, but now I get an exception which says: 

    "Session state has created a session id, but cannot save it because the response was already flushed by the application.

    An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code."

    When I debug the program I can see that the api request called twice (I dont know why), on the first call the file is generated successfully but the response doesnt returned to the client. On the second call it doesnt work at all.

    This is my code:

    HTML:

    <button

                class="col-sm-2 button-style button-text"

                style="color: white; background-color: #19D893;height: 100%;"

                (click)="exportPriceList()">

            Export

            </button>

    TypeScript:

    public exportPriceList():  void {

        console.log('start export to excel');

      

        const fileName = 'PriceList_' + this.auth.authDetails.getValue().bank + '_' + Date.now.toString() + '.xlsx';

        const fileType = 'application/vnd.ms-excel';

        let url;

        if (this.auth.authDetails.getValue().isBoi)

        {

         url = this.apiService.baseUrl + 'api/PriceList/Export?token='  + this.token +

        '&priceListType=' + this.selectedPriceListType.Key +   '&bank=' + this.selectedBank.Key  ;

        }

        else

        {

          url = this.apiService.baseUrl + 'api/PriceList/Export?token='  + this.token +

          '&priceListType=' + this.selectedPriceListType.Key;

        }

    //     const file = new Blob([content], {type: 'text/plain'});

    // FileSaver.saveAs(file, "test.txt");

       const promise = new Promise((resolve, reject) => {                                

          this.http.post(url,   '' ,

             {

                headers: new HttpHeaders({

                'Content-Type':  'application/json'

               }), responseType: 'blob'

             }).subscribe(success => {

               console.log('start success');

              const blob = new Blob ([success], {type: fileType});

             

    //FileSaver.saveAs(blob, fileName);

              console.log('window.navigator ', window.navigator  );

              console.log('window.navigator.msSaveOrOpenBlob ', window.navigator.msSaveOrOpenBlob  );

       

              if (window.navigator && window.navigator.msSaveOrOpenBlob) {

               

       

                window.navigator.msSaveOrOpenBlob(blob, );

              }

               else {

                  const a = document.createElement('a');

                  a.href = URL.createObjectURL(blob);

                  a.download = fileName ;

                  document.body.appendChild(a);

                  a.click();

                  document.body.removeChild(a);

              }

          },

          err => {

              alert(err);

          });

         

       });

         promise.then((res) => {

           console.log('promise!!!! ', res );

        });

        promise.catch((err) => {

        });

          }

       

      }

    }

    API Controller:

    [HttpPost]

            [Route("api/PriceList/Export")]

            public HttpResponseMessage Export([FromUri]string token, [FromUri]int priceListType, [FromUri]int? bank=null)

            {

                try

                {

                    var stream = dal.ExportPriceListServer(priceListType, bank);

                    var response = new HttpResponseMessage(System.Net.HttpStatusCode.OK);

                    response.Content = new StreamContent(stream);

                    response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment");

                    response.Content.Headers.ContentDisposition.FileName = "PriceList_" + bank + "_" + DateTime.Now.ToString("yyyyMMdd") + ".xlsx";

                    response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/vnd.ms-excel");

                    //response.Content.Headers.ContentLength = stream.Length;

                    response.StatusCode = System.Net.HttpStatusCode.OK;

                    return response;

                }

                catch (Exception ex)

                {

                    exc.throwException(EventLogEntryType.Error, ex.ToString());

                    throw;

                }

            }

    Create excel:           

      
    public MemoryStream CreateExcel(DataTable dt)
    
            {
    
                try
    
                {
    
                    XSSFWorkbook workbook = new XSSFWorkbook();
    
                    //FileStream fStream = new FileStream(Path.GetTempPath()+"test.xlsx", FileMode.OpenOrCreate, FileAccess.ReadWrite);
    
                    MemoryStream ms = new MemoryStream();
    
                    ///.......design the fle


    workbook.Write(ms);
    
                    return ms;
    
    
    
                }
    
                catch
    (System.Exception ex)
    
                {
    
                   
    Console.Write(ex);
    
                   
    Environment.Exit(-1);
    
                    return null;
    
                }
    
    
    
    
    
            }

    I have tried this solution

    Add to Global.asax:

    void Session_Start(object sender, EventArgs e)

    {

        // Code that runs when a new session is started

        string sessionId = Session.SessionID;

    }

    But it didn't solved the problem.

    Thanks In advance,

    Coral

    

    יום שני 25 מאי 2020 07:57

תשובות

כל התגובות