1
- using System . Collections . Generic ;
1
+ using System ;
2
+ using System . Collections . Generic ;
3
+ using System . Security . Cryptography ;
2
4
using System . Threading . Tasks ;
3
5
using Microsoft . AspNetCore . Components . Server . ProtectedBrowserStorage ;
4
6
@@ -13,10 +15,47 @@ public LocalStorageService(ProtectedLocalStorage localStorage)
13
15
this . localStorage = localStorage ;
14
16
}
15
17
16
- public async ValueTask < bool > ContainKeyAsync ( string key ) => ( await localStorage . GetAsync < object > ( key ) ) . Success ;
18
+ public async ValueTask < bool > ContainsKeyAsync ( string key )
19
+ {
20
+ try
21
+ {
22
+ return ( await localStorage . GetAsync < object > ( key ) ) . Success ;
23
+ }
24
+ catch ( CryptographicException )
25
+ {
26
+ await localStorage . DeleteAsync ( key ) ;
27
+ return false ;
28
+ }
29
+ }
17
30
18
- public async ValueTask < T > GetItemAsync < T > ( string key ) => ( await localStorage . GetAsync < T > ( key ) ) . Value
19
- ?? throw new KeyNotFoundException ( $ "Key { key } not found") ;
31
+ public async ValueTask < T > GetItemAsync < T > ( string key )
32
+ {
33
+ try
34
+ {
35
+ var result = await localStorage . GetAsync < T > ( key ) ;
36
+ if ( ! result . Success )
37
+ {
38
+ throw new KeyNotFoundException ( $ "Key { key } not found") ;
39
+ }
40
+ return result . Value ! ;
41
+ }
42
+ catch ( CryptographicException )
43
+ {
44
+ await localStorage . DeleteAsync ( key ) ;
45
+ throw new KeyNotFoundException ( $ "Key { key } was invalid and has been removed") ;
46
+ }
47
+ }
20
48
21
- public async ValueTask SetItemAsync < T > ( string key , T value ) => await localStorage . SetAsync ( key , value ! ) ;
49
+ public async ValueTask SetItemAsync < T > ( string key , T value )
50
+ {
51
+ try
52
+ {
53
+ await localStorage . SetAsync ( key , value ! ) ;
54
+ }
55
+ catch ( CryptographicException )
56
+ {
57
+ await localStorage . DeleteAsync ( key ) ;
58
+ throw new InvalidOperationException ( $ "Could not set value for key { key } . The key has been removed.") ;
59
+ }
60
+ }
22
61
}
0 commit comments