After migrating to ASP.NET Core 2.1 we have realized that some consumers of our API are sending GET requests with the Content-Type header set to application/json. Sadly, these requests have not been rejected in the past (even though they should have), nevertheless this still is a breaking change..
Since our consumers need to fix this issue on their end, and this will take some time, we would like to temporarily accept these requests so we're not stuck waiting for …
我正在尝试使用 FileStream 和 FileOptions.DeleteOnClose 创建一个临时文件。我在关闭流时看到了预期的行为,但是如果抛出异常,则不会删除文件。我无法使用,using因为流的关闭是由 FileStreamResult 处理的。我知道在 Windows 上它由 winapi 标志 FILE_FLAG_DELETE_ON_CLOSE 处理,但我不知道这是否/如何适用于 .NET Core 应用程序上的其他平台。
我已经尝试围绕这个包裹一个 try-catch 以在错误的情况下手动处理流,这确实有效,但应该是不必要的,因为一旦释放所有句柄,文件就会被删除。
const FileOptions fileOptions =
FileOptions.Asynchronous |
FileOptions.DeleteOnClose |
FileOptions.Encrypted |
FileOptions.SequentialScan;
var fileStream = new FileStream(
Path.GetRandomFileName(),
FileMode.Create,
FileAccess.ReadWrite,
FileShare.None,
4096,
fileOptions);
Run Code Online (Sandbox Code Playgroud)
如果 FileOptions.DeleteOnClose 是跨平台的,我希望在释放所有句柄时删除该文件,但该文件仍然存在。
从 C# 7 开始,我们可以使用丢弃_来丢弃未使用的变量。我使用它的一件事是在即发即忘的任务中。
考虑这个方法:
public Task Example()
{
// Do some fire-and-forget stuff.
}
Run Code Online (Sandbox Code Playgroud)
您可以通过简单地不等待任务来消除此任务:Example(),但是这仍然会给您一个警告。使用丢弃关键字,我们现在可以使用: _ = Example(),它消除了这个警告。我想知道这是否有任何我应该注意的令人讨厌的副作用?(除了 MSDN 声明的内容:“这具有抑制操作即将完成时抛出的异常的效果。”)