GVKun编程网logo

asp.net-core – Stream的意外结束,内容可能已被另一个组件读取. Microsoft.AspNetCore.WebUtilities.MultipartReaderStream

16

本文将带您了解关于asp.net-core–Stream的意外结束,内容可能已被另一个组件读取.Microsoft.AspNetCore.WebUtilities.MultipartReaderStr

本文将带您了解关于asp.net-core – Stream的意外结束,内容可能已被另一个组件读取. Microsoft.AspNetCore.WebUtilities.MultipartReaderStream的新内容,另外,我们还将为您提供关于.NET FileStream文件流,StreamReader文本流,MemoryStream内存流几种流的实例、.net – MultipartFormDataStreamProvider vs HttpContext.Current、asp.net – MultipartFormDataStreamProvider清理、asp.net – 不明确的引用问题(Microsoft.AspNet.Identity和Microsoft.AspNet.Identity.Core)的实用信息。

本文目录一览:

asp.net-core – Stream的意外结束,内容可能已被另一个组件读取. Microsoft.AspNetCore.WebUtilities.MultipartReaderStream

asp.net-core – Stream的意外结束,内容可能已被另一个组件读取. Microsoft.AspNetCore.WebUtilities.MultipartReaderStream

当我尝试从请求中读取多部分内容时,我得到一个异常,说明内容可能已被其他组件读取.

if (MultipartRequestHelper.IsMultipartContentType(Request.ContentType))
            {
                // Used to accumulate all the form url encoded key value pairs in the 
                // request.
                var formAccumulator = new keyvalueAccumulator();

                var boundary = Request.GetMultipartBoundary();
                var reader = new MultipartReader(boundary,HttpContext.Request.Body);
                var section = await reader.ReadNextSectionAsync();
                while (section != null)
                {
                    ContentdispositionHeaderValue contentdisposition;
                    var hasContentdispositionHeader =
                        ContentdispositionHeaderValue.TryParse(section.Contentdisposition,out contentdisposition);
                }
            }

解决方法

事实证明,我必须使用下面的属性禁用表单值模型绑定.

[HttpPost]
    [Route("")]
    [disableFormValueModelBinding]
    public async Task<IActionResult> Post()

属性实现如下

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
public class disableFormValueModelBindingAttribute : Attribute,IResourceFilter
{
    public void OnResourceExecuting(ResourceExecutingContext context)
    {
        var factories = context.ValueProviderFactories;
        factories.RemoveType<FormValueProviderFactory>();
        factories.RemoveType<JQueryFormValueProviderFactory>();
    }

    public void OnResourceExecuted(ResourceExecutedContext context)
    {
    }
}

.NET FileStream文件流,StreamReader文本流,MemoryStream内存流几种流的实例

.NET FileStream文件流,StreamReader文本流,MemoryStream内存流几种流的实例

一、FileStream文件流

1.读取数据

 1    public class ReadFile
 2     {
 3         /// <summary>
 4         /// 读取文件
 5         /// FileMode.Create  创建一个新文件,如果文件已经存在则改写旧文件
 6         /// FileMode.CreateNew 创建一个文件,如果文件存在会发生异常,提示文件已经存在
 7         /// FileMode.Open  打开文件,如果文件不存在则异常
 8         /// FileMode.OpenOrCreate  打开文件,如果文件不存在,则创建一个新的文件并且打开文件
 9         /// FileMode.Append   打开现有文件,并且在现有文件内容后面追加,如果文件不存在则异常
10         /// FileMode.Truncate 根据现有操作系统,截取文件里面的内容,如果文件不存在则异常
11         /// </summary>
12         public static void Read(string FilePath)
13         {
14             FileStream fileStream = null;
15             try
16             {
17               fileStream = new FileStream(FilePath, FileMode.Truncate);
18                 byte[] bytes = new byte[fileStream.Length];
19                 int read = fileStream.Read(bytes, 0, bytes.Length);
20                 var result = Encoding.UTF8.GetString(bytes);
21             }
22             catch (Exception e)
23             {
24                 if (fileStream != null)
25                 {
26                     fileStream.Dispose();
27                 }
28                 Console.WriteLine(e.Message);
29             }
30             finally
31             {
32                 if (fileStream != null)
33                 {
34                     fileStream.Close();
35                     fileStream.Dispose();
36                 }
37             }
38         }
39     }

2.写入数据

 1    public class WriteFile
 2     {
 3         public static void WriteText(string FilePath,string writeString)
 4         {
 5             FileStream fileStream = null;
 6             try
 7             {
 8                 //根据路径打开文件
 9                 fileStream = new FileStream(@"C:\Users\Administrator\source\repos\OperatFile\OperatFile\1.txt", FileMode.Append);
10                 //把字符串转化成字节
11                 byte[] bytes = Encoding.UTF8.GetBytes(writeString);
12                 //写入到文件
13                 fileStream.Write(bytes, 0, bytes.Length);
14             }
15             catch (Exception e)
16             {
17           if (fileStream != null)
18                 {
19                     fileStream.Dispose();
20                 }
21                 Console.WriteLine(e.Message);
22             }
23             finally
24             {
25                 //关闭和释放
26                 if (fileStream != null)
27                 {
28                     fileStream.Close();
29                     fileStream.Dispose();
30                 }
31             }
32         }
33     }

二、StreamReader文本流

1.读取数据

 1    public class SteamReadFile
 2     {
 3         /// <summary>
 4         /// 读取文件
 5         /// </summary>
 6         /// <param name="filePath">文件路径</param>
 7         public static void ReadFile(string FilePath)
 8         {
 9             try
10             {
11                 using (StreamReader sr = new StreamReader(FilePath))
12                 {
13                     var result = sr.ReadToEnd();
14                     Console.WriteLine(result);
15                 }
16             }
17             catch (Exception e)
18             {
19 
20                 throw new Exception(e.Message);
21             }
22         }
23     }

2.写入数据

 1    public class StreamWriteFile
 2     {
 3         /// <summary>
 4         /// 写入文件
 5         /// </summary>
 6         /// <param name="FilePath">文件路径</param>
 7         /// <param name="WriteString">待写入字符串</param>
 8         public static void WriteFile(string FilePath,string WriteString)
 9         {
10             try
11             {
12                 using (StreamWriter sr = new StreamWriter(FilePath))
13                 {
14                     sr.WriteLine(WriteString);
15                 }
16             }
17             catch (Exception e)
18             {
19                 throw new Exception(e.Message);
20             }
21         }
22     }

3.写入日志实例

 1    public class LogHelper
 2     {
 3         /// <summary>
 4         /// 文件路径
 5         /// </summary>
 6         public static string FilePath = @"C:\Users\Administrator\source\repos\OperatFile\OperatFile\Files";
 7         static LogHelper()
 8         {
 9             //判断文件夹是否存在,如果不存在,则重新创建
10             if (!Directory.Exists(FilePath))
11             {
12                 Directory.CreateDirectory(FilePath);
13             }
14         }
15      /// <summary>
16         /// 日志写入
17         /// Path.Combine(str1,str2,str3)  把传入的参数拼接起来,然后返回新的字符串
18         /// File.AppendText(fullPath) 根据文件路径,把新写入的内容,拼接到文本后面
19         /// </summary>
20         public static void WriteLog()
21         {
22             try
23             {
24                 var sb = BindData();
25                 string fullPath = Path.Combine(FilePath, $"{DateTime.Now.ToString("yyyy-MM-dd")}.txt");
26                 //判断文件是否存在,如果不存在,则新建文件
27                 if (!File.Exists(fullPath))
28                 {
29                     File.Create(fullPath);
30                 }
31                 using (StreamWriter sw = File.AppendText(fullPath))
32                 {
33                     sw.WriteLine(sb.ToString());
34                 }
35             }
36             catch (Exception e)
37             {
38                 throw new Exception(e.Message);
39             }
40 
41         }
42      /// <summary>
43         /// 绑定日志信息
44         /// </summary>
45         /// <returns></returns>
46         private static StringBuilder BindData()
47         {
48             StringBuilder sb = new StringBuilder();
49             DateTime operatDateTime = DateTime.Now;
50             string content = "读写文件功能";
51             string operators = "小明";
52             sb.AppendLine($"操作时间:{operatDateTime}");
53             sb.AppendLine($"操作内容:{content}");
54             sb.AppendLine($"操作人:{operators}");
55             sb.AppendLine("------------------------------------------------------------------------------------------");
56             return sb;
57         }
58     }

三、MemoryStream内存流

 1      /// <summary>
 2         /// 根据URL读取内容到内存流
 3         /// </summary>
 4         /// <param name="url"></param>
 5         /// <returns></returns>
 6         public static string DownLoadByUrl(string url)
 7         {
 8             string result = string.Empty;
 9             MemoryStream ms = null;
10             HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
11             HttpWebResponse response = request.GetResponse() as HttpWebResponse;
12             using (var stream = response.GetResponseStream())
13             {
14           byte[] buffer = new byte[response.ContentLength];
15                 int actuallyRead = 0, offset = 0;
16                 do
17                 {
18                     actuallyRead = stream.Read(buffer, offset, buffer.Length - offset);
19                     offset += actuallyRead;
20 
21                 } while (actuallyRead > 0);
22                 ms = new MemoryStream(buffer);
23                 ms.Seek(0, SeekOrigin.Begin);
24                 var byteArray = new byte[ms.Length];
25                 ms.Read(byteArray, 0, byteArray.Length);
26                 result = Encoding.UTF8.GetString(byteArray);
27             }
28             response.Close();
29             response.Dispose();
30             return result;
31         }

 

.net – MultipartFormDataStreamProvider vs HttpContext.Current

.net – MultipartFormDataStreamProvider vs HttpContext.Current

我很难理解为什么在使用HttpContext.Current获取所有信息时,我想使用MultipartFormDataStreamProvider。

这样做容易得多:

var mydata = HttpContext.Current.Request.Form["mydata"];

比这个:

string root = HttpContext.Current.Server.MapPath("~/somedir");
var provider = new MultipartFormDataStreamProvider(root);

this.Request.Content.ReadAsMultipartAsync(provider).ContinueWith(t =>
{
    var mydata = provider.Contents.First(c => c.Headers.Contentdisposition.Name == "\"mydata\"").ReadAsstringAsync().Result;
});

PS – 我正在尝试构建一个ApiController来接受文件上传。我读过这篇文章http://www.asp.net/web-api/overview/working-with-http/sending-html-form-data,-part-2。

解决方法

这是我在 MSDN发现的。我想这可能会帮助你。

流提供者查看Content-disposition头域,并根据文件名参数的存在确定输出流。如果在Content-disposition头域中存在文件名参数,则将Body部分写入FileStream,否则将其写入MemoryStream。这使得可以方便地处理作为表单数据和文件内容的组合的MIME Multipart HTML Form数据。

asp.net – MultipartFormDataStreamProvider清理

asp.net – MultipartFormDataStreamProvider清理

如果文件发布到我的webapp,那么我通过MultipartFormDataStreamProvider.FileData读取它们.

我像这样初始化提供者:

string root = HttpContext.Current.Server.MapPath("~/App_Data");
var provider = new MultipartFormDataStreamProvider(root);

并且提供者很好地将它们存储为“~App_Data / BodyPart_ {someguid}”
但是,在完成这些文件后,如何清理这些文件?

解决方法

您可以删除所有超过特定时间跨度的文件.例如
private void CleanTempFiles(string dir,int ageInMinutes)
{
    string[] files = Directory.GetFiles(dir);

    foreach (string file in files)
    {
        var time = File.GetCreationTime(file);

        if (time.AddMinutes(ageInMinutes) < DateTime.Now)
        {
            File.Delete(file);
        }
    }
}

然后用以下内容调用它:

CleanTempFiles(root,60); // Delete all files older than 1 hour

asp.net – 不明确的引用问题(Microsoft.AspNet.Identity和Microsoft.AspNet.Identity.Core)

asp.net – 不明确的引用问题(Microsoft.AspNet.Identity和Microsoft.AspNet.Identity.Core)

我正在使用最新的VS2015社区和ASP.NET 5等构建AngularJS单页面应用程序…

我在尝试实现身份验证时遇到的问题是我需要使用这两个命名空间:

Microsoft.AspNet.Identity //Version 3.0.0-beta4
Microsoft.AspNet.Identity.Owin //Version 2.2.1

但由于Microsoft.AspNet.Identity.Owin具有依赖性

Microsoft.AspNet.Identity.Core

我不断得到模糊的引用问题,例如对于Microsoft.AspNet.Identity和Microsoft.AspNet.Identity.Core中存在的UserManager.

之前还有其他人处理过这件事吗?
它是版本不兼容问题还是仅仅是不完整的Owin ASP.NET 5实现?

解决方法

Microsoft.AspNet.Identity.Owin包是ASP.NET Identity 2的一部分,而不是ASP.NET 5附带的最新版本.尝试引用它将下载ASP.NET Identity 2并导致您遇到的奇怪错误.

只需引用Microsoft.AspNet.Identity即可.

关于asp.net-core – Stream的意外结束,内容可能已被另一个组件读取. Microsoft.AspNetCore.WebUtilities.MultipartReaderStream的介绍已经告一段落,感谢您的耐心阅读,如果想了解更多关于.NET FileStream文件流,StreamReader文本流,MemoryStream内存流几种流的实例、.net – MultipartFormDataStreamProvider vs HttpContext.Current、asp.net – MultipartFormDataStreamProvider清理、asp.net – 不明确的引用问题(Microsoft.AspNet.Identity和Microsoft.AspNet.Identity.Core)的相关信息,请在本站寻找。

本文标签: