2

I am making web app and i have web api where I save data in file in async function :

    [HttpPost]
    [Route("~/api/data/savetemplate")]
    public async void Savetemplate()
    {
        try
        {
            string result = await Request.Content.ReadAsStringAsync();                
            JObject jobject = JObject.Parse(result);
            Debug.WriteLine(jobject);
            JToken id_token = jobject.Property("id").Value;
            string id = id_token.ToString();
            id = id.Replace("-", "");
            id = id.Replace(" ", "");
            id = id.Replace(":", "");
            id = id.Replace(".", "");
            string path = @"C:\client\" + id + "_template.json";
            File.WriteAllText(path, jobject.ToString());

            // write JSON directly to a file
            using (StreamWriter file = File.CreateText(path))
            using (JsonTextWriter writer = new JsonTextWriter(file))
            {
                jobject.WriteTo(writer);
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex);
            throw;
        }           
    }

First time it works, but when I try again this exception appears :

    System.Net.Http.HttpRequestException was unhandled by user code
    HResult=-2146233088
    Message=Error while copying content to a stream.
    Source=mscorlib
    StackTrace:
    at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
    at   System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
   at Invent.DataController.<SaveSagatave>d__0.MoveNext() in  c:\Invent\DataCtrl.cs:line 211
   InnerException: System.ObjectDisposedException
   HResult=-2146232798
   Message=Cannot access a disposed object.
   Source=System.Web.Http.Owin
   ObjectName=""
   StackTrace:
        at System.Web.Http.NonOwnedStream.ThrowIfDisposed()
        at System.Web.Http.NonOwnedStream.EndRead(IAsyncResult asyncResult)
        at System.Net.Http.StreamToStreamCopy.BufferReadCallback(IAsyncResult ar)
   InnerException: 

I guess problem is that, the object is disposed, but how can I fix, that object isnt disposed?

UPDATE : It throws exception at string result = await Request.Content.ReadAsStringAsync();

Imants Volkovs
  • 838
  • 11
  • 20

0 Answers0