【发布时间】:2021-09-06 03:57:27
【问题描述】:
我在我的代码中使用StreamReader,如下所示:
string json = await new StreamReader(context.Request.Body).ReadToEndAsync();
// ... use json variable here in some other code
我偶然发现了using 声明。我的第一个语句与使用using 语句和StreamReader 之间有什么区别吗?
我应该在产品代码中使用using 语句和StreamReader 吗?
string json;
using (var reader = new StreamReader(context.Request.Body))
{
json = await reader.ReadToEndAsync();
}
【问题讨论】:
-
对于您的特殊情况,
context.Request.Body将被处置,无论其是否由框架拥有和管理。流阅读器可以采用构造重载来保持流打开,尽管它在这里并不是很有用。此外,由于这可能是 json,因此还有其他方法可以实现这一点,即将流/主体直接传递给 json 反序列化器(等等)。 -
有一种新的 using 语法可以减少分解/嵌套代码:
using var reader = new StreamReader(...); var json = reader.Read...。看看吧 -
你可以跳过所有这些低级字符串/阅读器的麻烦,让http请求为你解压你的json到一个类,见docs.microsoft.com/en-us/dotnet/api/…
-
虽然我同意这是关于
using的问题。我确实认为这个问题专门询问如何使用HttpRequest处理using,从而使其比建议的副本更具体。
标签: c# asp.net-core streamreader using