从网上阅读并多次写入文件

时间:2014-07-28 07:26:22

标签: c# asynchronous

我正在制作网络应用程序,我有web api,我在async函数中保存数据:

    [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;
        }           
    }

首次使用,但是当我再次尝试时,会出现此异常:

    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: 

我猜问题就是,对象被处理了,但我怎么能修复,那个对象不被处理?

更新:它抛出异常         string result = await Request.Content.ReadAsStringAsync();

0 个答案:

没有答案