Skip to content
This repository was archived by the owner on Apr 12, 2023. It is now read-only.

Commit d61f68b

Browse files
authored
Merge pull request #63 from microsoftgraph/netcore3.1
Migrating to ASP.NET Core 3.1
2 parents bc4abf0 + 6d0bba1 commit d61f68b

File tree

12 files changed

+67
-83
lines changed

12 files changed

+67
-83
lines changed

MicrosoftGraphAspNetCoreConnectSample/Controllers/HomeController.cs

Lines changed: 8 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -6,25 +6,22 @@
66
using System.Threading.Tasks;
77
using Microsoft.AspNetCore.Authorization;
88
using Microsoft.AspNetCore.Mvc;
9-
using MicrosoftGraphAspNetCoreConnectSample.Helpers;
10-
using Microsoft.Extensions.Configuration;
119
using Microsoft.Graph;
1210
using Microsoft.AspNetCore.Hosting;
1311
using System.Security.Claims;
12+
using MicrosoftGraphAspNetCoreConnectSample.Services;
1413

1514
namespace MicrosoftGraphAspNetCoreConnectSample.Controllers
1615
{
1716
public class HomeController : Controller
1817
{
19-
private readonly IConfiguration _configuration;
20-
private readonly IHostingEnvironment _env;
21-
private readonly IGraphSdkHelper _graphSdkHelper;
18+
private readonly IWebHostEnvironment _env;
19+
private readonly IGraphServiceClientFactory _graphServiceClientFactory;
2220

23-
public HomeController(IConfiguration configuration, IHostingEnvironment hostingEnvironment, IGraphSdkHelper graphSdkHelper)
21+
public HomeController(IWebHostEnvironment hostingEnvironment, IGraphServiceClientFactory graphServiceClientFactory)
2422
{
25-
_configuration = configuration;
2623
_env = hostingEnvironment;
27-
_graphSdkHelper = graphSdkHelper;
24+
_graphServiceClientFactory = graphServiceClientFactory;
2825
}
2926

3027
[AllowAnonymous]
@@ -34,11 +31,11 @@ public async Task<IActionResult> Index(string email)
3431
if (User.Identity.IsAuthenticated)
3532
{
3633
// Get users's email.
37-
email = email ?? User.FindFirst("preferred_username")?.Value;
34+
email ??= User.FindFirst("preferred_username")?.Value;
3835
ViewData["Email"] = email;
3936

4037
// Initialize the GraphServiceClient.
41-
var graphClient = _graphSdkHelper.GetAuthenticatedClient((ClaimsIdentity)User.Identity);
38+
var graphClient = _graphServiceClientFactory.GetAuthenticatedGraphClient((ClaimsIdentity)User.Identity);
4239

4340
ViewData["Response"] = await GraphService.GetUserJson(graphClient, email, HttpContext);
4441

@@ -62,7 +59,7 @@ public async Task<IActionResult> SendEmail(string recipients)
6259
try
6360
{
6461
// Initialize the GraphServiceClient.
65-
var graphClient = _graphSdkHelper.GetAuthenticatedClient((ClaimsIdentity)User.Identity);
62+
var graphClient = _graphServiceClientFactory.GetAuthenticatedGraphClient((ClaimsIdentity)User.Identity);
6663

6764
// Send the email.
6865
await GraphService.SendEmail(graphClient, _env, recipients, HttpContext);

MicrosoftGraphAspNetCoreConnectSample/Extensions/AzureAdAuthenticationBuilderExtensions.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@
66
using Microsoft.Extensions.Options;
77
using Microsoft.IdentityModel.Protocols.OpenIdConnect;
88
using Microsoft.IdentityModel.Tokens;
9-
using MicrosoftGraphAspNetCoreConnectSample.Helpers;
9+
using MicrosoftGraphAspNetCoreConnectSample.Services;
1010

1111
namespace MicrosoftGraphAspNetCoreConnectSample.Extensions
1212
{
Lines changed: 6 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,24 +1,18 @@
11
<Project Sdk="Microsoft.NET.Sdk.Web">
22

33
<PropertyGroup>
4-
<TargetFramework>netcoreapp2.1</TargetFramework>
5-
<UserSecretsId>aspnet-MicrosoftGraphAspNetCoreConnectSample-ec1d62b9-d84d-45c8-8b3e-dc4e8b2ed850</UserSecretsId>
6-
<WebProject_DirectoryAccessLevelKey>0</WebProject_DirectoryAccessLevelKey>
7-
<Version>2.0.0</Version>
4+
<TargetFramework>netcoreapp3.1</TargetFramework>
5+
<Version>3.0.0</Version>
86
<Authors>Mark Szabo</Authors>
97
<Company>Microsoft</Company>
108
<Product>Microsoft Graph</Product>
119
</PropertyGroup>
1210

1311
<ItemGroup>
14-
<PackageReference Include="Microsoft.AspNetCore.App" />
15-
<PackageReference Include="Microsoft.Graph" Version="1.16.0" />
16-
<PackageReference Include="Microsoft.Identity.Client" Version="4.2.1" />
17-
<PackageReference Include="Newtonsoft.Json" Version="12.0.2" />
18-
</ItemGroup>
19-
20-
<ItemGroup>
21-
<DotNetCliToolReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Tools" Version="2.0.0" />
12+
<PackageReference Include="Microsoft.AspNetCore.Authentication.OpenIdConnect" Version="3.1.5" />
13+
<PackageReference Include="Microsoft.Graph" Version="3.8.0" />
14+
<PackageReference Include="Microsoft.Identity.Client" Version="4.16.1" />
15+
<PackageReference Include="Newtonsoft.Json" Version="12.0.3" />
2216
</ItemGroup>
2317

2418
</Project>

MicrosoftGraphAspNetCoreConnectSample/Program.cs

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55

66
using Microsoft.AspNetCore;
77
using Microsoft.AspNetCore.Hosting;
8+
using Microsoft.Extensions.Logging;
89

910
namespace MicrosoftGraphAspNetCoreConnectSample
1011
{
@@ -17,6 +18,11 @@ public static void Main(string[] args)
1718

1819
public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
1920
WebHost.CreateDefaultBuilder(args)
21+
.ConfigureLogging((hostingContext, logging) =>
22+
{
23+
logging.AddConsole();
24+
logging.AddDebug();
25+
})
2026
.UseStartup<Startup>();
2127
}
2228
}

MicrosoftGraphAspNetCoreConnectSample/Helpers/GraphAuthProvider.cs renamed to MicrosoftGraphAspNetCoreConnectSample/Services/GraphAuthProvider.cs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -10,11 +10,11 @@
1010
using Microsoft.Graph;
1111
using MicrosoftGraphAspNetCoreConnectSample.Extensions;
1212

13-
namespace MicrosoftGraphAspNetCoreConnectSample.Helpers
13+
namespace MicrosoftGraphAspNetCoreConnectSample.Services
1414
{
1515
public class GraphAuthProvider : IGraphAuthProvider
1616
{
17-
private IConfidentialClientApplication _app;
17+
private readonly IConfidentialClientApplication _app;
1818
private readonly string[] _scopes;
1919

2020
public GraphAuthProvider(IConfiguration configuration)

MicrosoftGraphAspNetCoreConnectSample/Helpers/GraphService.cs renamed to MicrosoftGraphAspNetCoreConnectSample/Services/GraphService.cs

Lines changed: 11 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -13,10 +13,12 @@
1313
using System.Linq;
1414
using System.Threading.Tasks;
1515

16-
namespace MicrosoftGraphAspNetCoreConnectSample.Helpers
16+
namespace MicrosoftGraphAspNetCoreConnectSample.Services
1717
{
1818
public static class GraphService
1919
{
20+
private const string PlaceholderImage = "data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iVVRGLTgiPz4NCjwhRE9DVFlQRSBzdmcgIFBVQkxJQyAnLS8vVzNDLy9EVEQgU1ZHIDEuMS8vRU4nICAnaHR0cDovL3d3dy53My5vcmcvR3JhcGhpY3MvU1ZHLzEuMS9EVEQvc3ZnMTEuZHRkJz4NCjxzdmcgd2lkdGg9IjQwMXB4IiBoZWlnaHQ9IjQwMXB4IiBlbmFibGUtYmFja2dyb3VuZD0ibmV3IDMxMi44MDkgMCA0MDEgNDAxIiB2ZXJzaW9uPSIxLjEiIHZpZXdCb3g9IjMxMi44MDkgMCA0MDEgNDAxIiB4bWw6c3BhY2U9InByZXNlcnZlIiB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciPg0KPGcgdHJhbnNmb3JtPSJtYXRyaXgoMS4yMjMgMCAwIDEuMjIzIC00NjcuNSAtODQzLjQ0KSI+DQoJPHJlY3QgeD0iNjAxLjQ1IiB5PSI2NTMuMDciIHdpZHRoPSI0MDEiIGhlaWdodD0iNDAxIiBmaWxsPSIjRTRFNkU3Ii8+DQoJPHBhdGggZD0ibTgwMi4zOCA5MDguMDhjLTg0LjUxNSAwLTE1My41MiA0OC4xODUtMTU3LjM4IDEwOC42MmgzMTQuNzljLTMuODctNjAuNDQtNzIuOS0xMDguNjItMTU3LjQxLTEwOC42MnoiIGZpbGw9IiNBRUI0QjciLz4NCgk8cGF0aCBkPSJtODgxLjM3IDgxOC44NmMwIDQ2Ljc0Ni0zNS4xMDYgODQuNjQxLTc4LjQxIDg0LjY0MXMtNzguNDEtMzcuODk1LTc4LjQxLTg0LjY0MSAzNS4xMDYtODQuNjQxIDc4LjQxLTg0LjY0MWM0My4zMSAwIDc4LjQxIDM3LjkgNzguNDEgODQuNjR6IiBmaWxsPSIjQUVCNEI3Ii8+DQo8L2c+DQo8L3N2Zz4NCg==";
21+
2022
// Load user's profile in formatted JSON.
2123
public static async Task<string> GetUserJson(GraphServiceClient graphClient, string email, HttpContext httpContext)
2224
{
@@ -58,6 +60,8 @@ public static async Task<string> GetPictureBase64(GraphServiceClient graphClient
5860
// Load user's profile picture.
5961
var pictureStream = await GetPictureStream(graphClient, email, httpContext);
6062

63+
if (pictureStream == null) return PlaceholderImage;
64+
6165
// Copy stream to MemoryStream object so that it can be converted to byte array.
6266
var pictureMemoryStream = new MemoryStream();
6367
await pictureStream.CopyToAsync(pictureMemoryStream);
@@ -72,16 +76,12 @@ public static async Task<string> GetPictureBase64(GraphServiceClient graphClient
7276
}
7377
catch (Exception e)
7478
{
75-
switch (e.Message)
79+
return e.Message switch
7680
{
77-
case "ResourceNotFound":
78-
// If picture not found, return the default image.
79-
return "data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iVVRGLTgiPz4NCjwhRE9DVFlQRSBzdmcgIFBVQkxJQyAnLS8vVzNDLy9EVEQgU1ZHIDEuMS8vRU4nICAnaHR0cDovL3d3dy53My5vcmcvR3JhcGhpY3MvU1ZHLzEuMS9EVEQvc3ZnMTEuZHRkJz4NCjxzdmcgd2lkdGg9IjQwMXB4IiBoZWlnaHQ9IjQwMXB4IiBlbmFibGUtYmFja2dyb3VuZD0ibmV3IDMxMi44MDkgMCA0MDEgNDAxIiB2ZXJzaW9uPSIxLjEiIHZpZXdCb3g9IjMxMi44MDkgMCA0MDEgNDAxIiB4bWw6c3BhY2U9InByZXNlcnZlIiB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciPg0KPGcgdHJhbnNmb3JtPSJtYXRyaXgoMS4yMjMgMCAwIDEuMjIzIC00NjcuNSAtODQzLjQ0KSI+DQoJPHJlY3QgeD0iNjAxLjQ1IiB5PSI2NTMuMDciIHdpZHRoPSI0MDEiIGhlaWdodD0iNDAxIiBmaWxsPSIjRTRFNkU3Ii8+DQoJPHBhdGggZD0ibTgwMi4zOCA5MDguMDhjLTg0LjUxNSAwLTE1My41MiA0OC4xODUtMTU3LjM4IDEwOC42MmgzMTQuNzljLTMuODctNjAuNDQtNzIuOS0xMDguNjItMTU3LjQxLTEwOC42MnoiIGZpbGw9IiNBRUI0QjciLz4NCgk8cGF0aCBkPSJtODgxLjM3IDgxOC44NmMwIDQ2Ljc0Ni0zNS4xMDYgODQuNjQxLTc4LjQxIDg0LjY0MXMtNzguNDEtMzcuODk1LTc4LjQxLTg0LjY0MSAzNS4xMDYtODQuNjQxIDc4LjQxLTg0LjY0MWM0My4zMSAwIDc4LjQxIDM3LjkgNzguNDEgODQuNjR6IiBmaWxsPSIjQUVCNEI3Ii8+DQo8L2c+DQo8L3N2Zz4NCg==";
80-
case "EmailIsNull":
81-
return JsonConvert.SerializeObject(new { Message = "Email address cannot be null." }, Formatting.Indented);
82-
default:
83-
return null;
84-
}
81+
"ResourceNotFound" => PlaceholderImage, // If picture is not found, return the placeholder image.
82+
"EmailIsNull" => JsonConvert.SerializeObject(new { Message = "Email address cannot be null." }, Formatting.Indented),
83+
_ => null,
84+
};
8585
}
8686
}
8787

@@ -183,7 +183,7 @@ public static async Task<Stream> GetMyPictureStream(GraphServiceClient graphClie
183183
}
184184

185185
// Send an email message from the current user.
186-
public static async Task SendEmail(GraphServiceClient graphClient, IHostingEnvironment hostingEnvironment, string recipients, HttpContext httpContext)
186+
public static async Task SendEmail(GraphServiceClient graphClient, IWebHostEnvironment hostingEnvironment, string recipients, HttpContext httpContext)
187187
{
188188
if (recipients == null) return;
189189

MicrosoftGraphAspNetCoreConnectSample/Helpers/GraphSDKHelper.cs renamed to MicrosoftGraphAspNetCoreConnectSample/Services/GraphServiceClientFactory.cs

Lines changed: 9 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -3,27 +3,23 @@
33
* See LICENSE in the source repository root for complete license information.
44
*/
55

6-
using System.Collections.Generic;
6+
using Microsoft.Graph;
77
using System.Net.Http.Headers;
88
using System.Security.Claims;
9-
using Microsoft.Graph;
109

11-
namespace MicrosoftGraphAspNetCoreConnectSample.Helpers
10+
namespace MicrosoftGraphAspNetCoreConnectSample.Services
1211
{
13-
public class GraphSdkHelper : IGraphSdkHelper
12+
public class GraphServiceClientFactory : IGraphServiceClientFactory
1413
{
1514
private readonly IGraphAuthProvider _authProvider;
16-
private GraphServiceClient _graphClient;
1715

18-
public GraphSdkHelper(IGraphAuthProvider authProvider)
16+
public GraphServiceClientFactory(IGraphAuthProvider authProvider)
1917
{
2018
_authProvider = authProvider;
2119
}
2220

23-
// Get an authenticated Microsoft Graph Service client.
24-
public GraphServiceClient GetAuthenticatedClient(ClaimsIdentity userIdentity)
25-
{
26-
_graphClient = new GraphServiceClient(new DelegateAuthenticationProvider(
21+
public GraphServiceClient GetAuthenticatedGraphClient(ClaimsIdentity userIdentity) =>
22+
new GraphServiceClient(new DelegateAuthenticationProvider(
2723
async requestMessage =>
2824
{
2925
// Get user's id for token cache.
@@ -38,12 +34,10 @@ public GraphServiceClient GetAuthenticatedClient(ClaimsIdentity userIdentity)
3834
// This header identifies the sample in the Microsoft Graph service. If extracting this code for your project please remove.
3935
requestMessage.Headers.Add("SampleID", "aspnetcore-connect-sample");
4036
}));
41-
42-
return _graphClient;
43-
}
4437
}
45-
public interface IGraphSdkHelper
38+
39+
public interface IGraphServiceClientFactory
4640
{
47-
GraphServiceClient GetAuthenticatedClient(ClaimsIdentity userIdentity);
41+
GraphServiceClient GetAuthenticatedGraphClient(ClaimsIdentity userIdentity);
4842
}
4943
}

MicrosoftGraphAspNetCoreConnectSample/Startup.cs

Lines changed: 13 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -10,14 +10,11 @@
1010
using Microsoft.AspNetCore.Hosting;
1111
using Microsoft.AspNetCore.Http;
1212
using Microsoft.AspNetCore.HttpsPolicy;
13-
using Microsoft.AspNetCore.Mvc;
1413
using Microsoft.Extensions.Configuration;
1514
using Microsoft.Extensions.DependencyInjection;
16-
using Microsoft.Extensions.Logging;
15+
using Microsoft.Extensions.Hosting;
1716
using MicrosoftGraphAspNetCoreConnectSample.Extensions;
18-
using MicrosoftGraphAspNetCoreConnectSample.Helpers;
19-
20-
17+
using MicrosoftGraphAspNetCoreConnectSample.Services;
2118

2219
namespace MicrosoftGraphAspNetCoreConnectSample
2320
{
@@ -51,28 +48,25 @@ public void ConfigureServices(IServiceCollection services)
5148
.AddAzureAd(options => Configuration.Bind("AzureAd", options))
5249
.AddCookie();
5350

54-
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
55-
56-
services.AddSession();
51+
services.AddMvc();
52+
services.AddControllers();
5753

5854
// Add application services.
59-
//services.AddSingleton<IConfiguration>(Configuration);
6055
services.AddSingleton<IGraphAuthProvider, GraphAuthProvider>();
61-
services.AddTransient<IGraphSdkHelper, GraphSdkHelper>();
56+
services.AddSingleton<IGraphServiceClientFactory, GraphServiceClientFactory>();
6257

6358
services.Configure<HstsOptions>(options =>
6459
{
6560
options.IncludeSubDomains = true;
6661
options.MaxAge = TimeSpan.FromDays(365);
6762
});
63+
64+
services.AddHealthChecks();
6865
}
6966

7067
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
71-
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
68+
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
7269
{
73-
loggerFactory.AddConsole(Configuration.GetSection("Logging"));
74-
loggerFactory.AddDebug();
75-
7670
if (env.IsDevelopment())
7771
{
7872
app.UseDeveloperExceptionPage();
@@ -85,14 +79,13 @@ public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerF
8579
app.UseHttpsRedirection();
8680
app.UseStaticFiles();
8781
app.UseCookiePolicy();
88-
app.UseSession();
82+
app.UseRouting();
8983
app.UseAuthentication();
90-
91-
app.UseMvc(routes =>
84+
app.UseAuthorization();
85+
app.UseEndpoints(endpoints =>
9286
{
93-
routes.MapRoute(
94-
name: "default",
95-
template: "{controller=Home}/{action=Index}/{id?}");
87+
endpoints.MapHealthChecks("/healthcheck");
88+
endpoints.MapControllerRoute("default", "{controller=Home}/{action=Index}/{id?}");
9689
});
9790
}
9891
}

MicrosoftGraphAspNetCoreConnectSample/Views/Home/Index.cshtml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@
55
ViewData["Title"] = "Home Page";
66
}
77

8-
<h2>Microsoft Graph ASP.NET Core 2.1 Connect Sample</h2>
8+
<h2>Microsoft Graph ASP.NET Core 3.1 Connect Sample</h2>
99

1010
@if (!User.Identity.IsAuthenticated)
1111
{

MicrosoftGraphAspNetCoreConnectSample/Views/Shared/_Layout.cshtml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -48,7 +48,7 @@
4848
@RenderBody()
4949
<hr />
5050
<footer>
51-
<p>&copy; 2018 - Microsoft</p>
51+
<p>&copy; 2020 - Microsoft</p>
5252
</footer>
5353
</div>
5454

0 commit comments

Comments
 (0)