1
+ using Grpc . Core ;
1
2
using Microsoft . AspNetCore . Http ;
2
3
using Microsoft . AspNetCore . Mvc ;
3
4
using Microsoft . Azure . Functions . Worker ;
@@ -18,15 +19,45 @@ public Contacts(HttpClientProvider httpClientProvider, ILogger<Contacts> logger)
18
19
}
19
20
20
21
[ Function ( "D365-CRM-Contacts" ) ]
21
- public async Task < IActionResult > Run ( [ HttpTrigger ( AuthorizationLevel . Function , "get" ) ] HttpRequest req )
22
+ public async Task < IActionResult > Run ( [ HttpTrigger ( AuthorizationLevel . Function , "get" , Route = "crm/contacts/{id?}" ) ] HttpRequest req , Guid ? id )
22
23
{
23
24
_logger . LogInformation ( "Dynamics365-CRM-Contacts is requested." ) ;
24
25
25
- var client = _httpClientProvider . Create ( ) ;
26
- var contactsJson = await client . GetStringAsync ( "contacts" ) ;
27
- var contacts = JsonValue . Parse ( contactsJson ) ;
26
+ try
27
+ {
28
+ var client = _httpClientProvider . Create ( ) ;
28
29
29
- return new OkObjectResult ( contacts ? [ "value" ] ) ;
30
+ if ( ! id . HasValue )
31
+ {
32
+ var contactsJson = await client . GetStringAsync ( "contacts?$select=contactid,fullname" ) ;
33
+ var contacts = JsonValue . Parse ( contactsJson ) ;
34
+ return new OkObjectResult ( contacts ? [ "value" ] ) ;
35
+ }
36
+
37
+ var contactResponse = await client . GetAsync ( $ "contacts({ id } )") ;
38
+ if ( ! contactResponse . IsSuccessStatusCode )
39
+ {
40
+ if ( contactResponse . StatusCode == System . Net . HttpStatusCode . NotFound )
41
+ {
42
+ return new NotFoundResult ( ) ;
43
+ }
44
+
45
+ // throws Exception
46
+ contactResponse . EnsureSuccessStatusCode ( ) ;
47
+ }
48
+
49
+ var contactJson = await contactResponse . Content . ReadAsStringAsync ( ) ;
50
+ return new ContentResult ( )
51
+ {
52
+ Content = contactJson ,
53
+ ContentType = "application/json"
54
+ } ;
55
+ }
56
+ catch ( HttpRequestException ex )
57
+ {
58
+ _logger . LogError ( ex , "An error has occured while processing Dynamics365-CRM-Contacts request." ) ;
59
+ return new StatusCodeResult ( ex . StatusCode . HasValue ? ( int ) ex . StatusCode . Value : StatusCodes . Status500InternalServerError ) ;
60
+ }
30
61
}
31
62
}
32
63
}
0 commit comments