rahularyansharma
rahularyansharma

Reputation: 10777

System.ObjectDisposedException: Cannot access a disposed object asp.net-core-webapi

I am using asp.net-core-webapi and I am also using iTextSharp to create pdf in memory steam.

[Route("preview/{Id}")]
        [System.Web.Http.HttpGet]
        public async Task<IActionResult> PreviewSpecSheet(int Id)
        {
            
            FileStreamResult fsr;

            Document document = new Document(PageSize.A4, 25, 25, 30, 30);
            using (MemoryStream ms = new MemoryStream())
            {

                using (PdfWriter writer = PdfWriter.GetInstance(document, ms))
                {



                    //PdfWriter writer = PdfWriter.GetInstance(document, ms);
                    document.Open();
                    //header Image 
                    iTextSharp.text.Image headerImg = iTextSharp.text.Image.GetInstance("D:\\go2\\Pixelle\\specsheet\\pixservice\\assets\\header.jpg");
                    headerImg.SetAbsolutePosition(0, 750);
                    headerImg.ScaleAbsolute(500f, 100.00f);
                    document.Add(headerImg);                    

                    fsr = File(ms, "application/pdf", "test.pdf");
                    return fsr;
                }
                 
            }
           
        }

I am getting following error :

System.ObjectDisposedException: Cannot access a disposed object.
Object name: 'Cannot access a closed file.'.
   at System.IO.FileStream.BeginRead(Byte[] array, Int32 offset, Int32 numBytes, AsyncCallback callback, Object state)
   at System.IO.Stream.<>c.<BeginEndReadAsync>b__48_0(Stream stream, ReadWriteParameters args, AsyncCallback callback, Object state)
   at System.Threading.Tasks.TaskFactory`1.FromAsyncTrim[TInstance,TArgs](TInstance thisRef, TArgs args, Func`5 beginMethod, Func`3 endMethod)
   at System.IO.Stream.BeginEndReadAsync(Byte[] buffer, Int32 offset, Int32 count)
   at System.IO.FileStream.ReadAsync(Byte[] buffer, Int32 offset, Int32 count, CancellationToken cancellationToken)
   at Microsoft.AspNetCore.Http.StreamCopyOperationInternal.CopyToAsync(Stream source, Stream destination, Nullable`1 count, Int32 bufferSize, CancellationToken cancel)
   at Microsoft.AspNetCore.Mvc.Infrastructure.FileResultExecutorBase.WriteFileAsync(HttpContext context, Stream fileStream, RangeItemHeaderValue range, Int64 rangeLength)
   at Microsoft.AspNetCore.Mvc.Infrastructure.FileStreamResultExecutor.ExecuteAsync(ActionContext context, FileStreamResult result)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeResultAsync>g__Logged|21_0(ResourceInvoker invoker, IActionResult result)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeNextResultFilterAsync>g__Awaited|29_0[TFilter,TFilterAsync](ResourceInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Rethrow(ResultExecutedContextSealed context)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.ResultNext[TFilter,TFilterAsync](State& next, Scope& scope, Object& state, Boolean& isCompleted)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.InvokeResultFilters()
--- End of stack trace from previous location where exception was thrown ---
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeFilterPipelineAsync>g__Awaited|19_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeAsync>g__Logged|17_1(ResourceInvoker invoker)
   at Microsoft.AspNetCore.Routing.EndpointMiddleware.<Invoke>g__AwaitRequestTask|6_0(Endpoint endpoint, Task requestTask, ILogger logger)
   at Microsoft.AspNetCore.Authorization.AuthorizationMiddleware.Invoke(HttpContext context)
   at Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)

Edited after apply comment solution :

If I remove using its working fine but when I am using

document.Close();
writer.Close();

before fsr = File(ms, "application/pdf", "test.pdf"); its again same error and if I dont close the document and writer , downloaded pdf is in corrupt format , not able to open.

after document.close() and writer.close() are used

enter image description here

Upvotes: 0

Views: 1254

Answers (1)

rahularyansharma
rahularyansharma

Reputation: 10777

Okay, So I am able to figure this out what was the issue.

In original code issue was using block , as already mentioned in comments section.

But when I removed using still facing issue of stream closing when I close document and writer .

and the reason is The PdfWriter class may be closing your stream. Make sure to set the CloseStream property to false.

so I set writer CloseStream property to false , just after declare.

PdfWriter writer = PdfWriter.GetInstance(document, ms);
 writer.CloseStream = false;

and its worked.

[Route("preview/{Id}")]
        [System.Web.Http.HttpGet]
        public async Task<IActionResult> PreviewSpecSheet(int Id)
        {
            
            FileStreamResult fsr;

            Document document = new Document(PageSize.A4, 25, 25, 30, 30);
            MemoryStream ms = new MemoryStream();


            PdfWriter writer = PdfWriter.GetInstance(document, ms);
            writer.CloseStream = false;



            
            document.Open();
            //header Image 
            iTextSharp.text.Image headerImg = iTextSharp.text.Image.GetInstance("D:\\go2\\Pixelle\\specsheet\\pixservice\\assets\\header.jpg");
            headerImg.SetAbsolutePosition(0, 750);
            headerImg.ScaleAbsolute(500f, 100.00f);
            document.Add(headerImg);

            

            document.Close();
            writer.Close();
            ms.Position = 0;
            fsr = File(ms, "application/pdf", "test.pdf");

            return fsr;
        }

Upvotes: 1

Related Questions