我正在使用 Azure 表存储从 MVC 应用程序记录访问者信息,但有时会引发以下异常:
[WebException: The remote server returned an error: (409) Conflict.]
System.Net.HttpWebRequest.GetResponse() +1399
Microsoft.WindowsAzure.Storage.Core.Executor.Executor.ExecuteSync(RESTCommand`1 cmd, IRetryPolicy policy, OperationContext operationContext) in c:\Program Files (x86)\Jenkins\workspace\release_dotnet_master\Lib\ClassLibraryCommon\Core\Executor\Executor.cs:677
[StorageException: The remote server returned an error: (409) Conflict.]
Microsoft.WindowsAzure.Storage.Core.Executor.Executor.ExecuteSync(RESTCommand`1 cmd, IRetryPolicy policy, OperationContext operationContext) in c:\Program Files (x86)\Jenkins\workspace\release_dotnet_master\Lib\ClassLibraryCommon\Core\Executor\Executor.cs:604
Microsoft.WindowsAzure.Storage.Table.TableOperation.Execute(CloudTableClient client, CloudTable table, TableRequestOptions requestOptions, OperationContext operationContext) in c:\Program Files (x86)\Jenkins\workspace\release_dotnet_master\Lib\ClassLibraryCommon\Table\TableOperation.cs:44
当我在一段时间不活动后第一次访问该网站时,似乎会发生这种情况,然后当我点击刷新时,页面会加载,从那时起每次点击都很好。
这是导致异常的代码部分:
var visit = new TrackerVisitEntity(id, url, referer);
var insertOperation = TableOperation.Insert(visit);
_table.Execute(insertOperation);
Update
正如评论和下面的两个答案中所指出的,问题是有时页面会连续快速加载两次,并且我使用 GUID(对用户唯一)作为分区键,并将当前日期时间作为行键,所以这会导致重复的实体并导致异常。
虽然Amor的回答比较深入,但Dogu的简单解决方案是我使用的,所以我标记了他的正确性。感谢大家。