This solution should help me explain my desire

This commit is contained in:
Tracy Pearson
2020-10-19 12:55:29 -04:00
parent 4e9964435b
commit 92445d4e7a
18 changed files with 280 additions and 71 deletions

View File

@@ -4,5 +4,10 @@
<TargetFramework>netcoreapp3.1</TargetFramework>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="..\RepositoryLibrary\RepositoryLibrary.csproj" />
<ProjectReference Include="..\SharedLibrary\SharedLibrary.csproj" />
</ItemGroup>
</Project>

View File

@@ -0,0 +1,26 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using RepositoryLibrary;
namespace ApiService.Controllers
{
[ApiController]
[Route("/api")]
public class RepositoryController : ControllerBase
{
private readonly IRepository _repsitory;
public RepositoryController(IRepository repository)
{
_repsitory = repository;
}
[HttpGet("lookup")]
public async Task<object> Lookup()
{
return await _repsitory.Lookup();
}
}
}

View File

@@ -1,39 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
namespace ApiService.Controllers
{
[ApiController]
[Route("[controller]")]
public class WeatherForecastController : ControllerBase
{
private static readonly string[] Summaries = new[]
{
"Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
};
private readonly ILogger<WeatherForecastController> _logger;
public WeatherForecastController(ILogger<WeatherForecastController> logger)
{
_logger = logger;
}
[HttpGet]
public IEnumerable<WeatherForecast> Get()
{
var rng = new Random();
return Enumerable.Range(1, 5).Select(index => new WeatherForecast
{
Date = DateTime.Now.AddDays(index),
TemperatureC = rng.Next(-20, 55),
Summary = Summaries[rng.Next(Summaries.Length)]
})
.ToArray();
}
}
}

View File

@@ -1,5 +1,4 @@
{
"$schema": "http://json.schemastore.org/launchsettings.json",
{
"iisSettings": {
"windowsAuthentication": false,
"anonymousAuthentication": true,
@@ -8,23 +7,21 @@
"sslPort": 0
}
},
"$schema": "http://json.schemastore.org/launchsettings.json",
"profiles": {
"IIS Express": {
"commandName": "IISExpress",
"launchBrowser": true,
"launchUrl": "weatherforecast",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
},
"ApiService": {
"commandName": "Project",
"launchBrowser": true,
"launchUrl": "weatherforecast",
"applicationUrl": "http://localhost:5000",
"launchUrl": "api/lookup",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
},
"applicationUrl": "http://localhost:56143"
}
}
}
}

View File

@@ -1,14 +1,21 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Runtime.Serialization.Json;
using System.Text;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using RepositoryLibrary;
using SharedLibrary.Models;
namespace ApiService
{
@@ -24,6 +31,7 @@ namespace ApiService
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddScoped<IRepository, LocalRepository>();
services.AddControllers();
}
@@ -37,6 +45,30 @@ namespace ApiService
app.UseRouting();
app.Use(async (context, next) =>
{
try
{
await next();
}
catch (Exception ex)
{
var error = new RepositoryError
{
Information = ex.Message,
StackTrack = ex.StackTrace
};
var dc = new DataContractJsonSerializer(typeof(RepositoryError));
using (var ms = new MemoryStream())
{
dc.WriteObject(ms, error);
var response = new StringBuilder(Encoding.UTF8.GetString(ms.ToArray()));
context.Response.StatusCode = (int)HttpStatusCode.BadRequest;
context.Response.ContentType = "application/json";
await context.Response.WriteAsync(response.ToString());
}
}
});
app.UseAuthorization();
app.UseEndpoints(endpoints =>

View File

@@ -1,15 +0,0 @@
using System;
namespace ApiService
{
public class WeatherForecast
{
public DateTime Date { get; set; }
public int TemperatureC { get; set; }
public int TemperatureF => 32 + (int)(TemperatureC / 0.5556);
public string Summary { get; set; }
}
}

View File

@@ -0,0 +1,69 @@
using SharedLibrary.Models;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;
namespace RepositoryLibrary
{
public class HostedRepository : IRepository
{
private readonly string _backendUrl;
public static ConcurrentBag<HttpClient> ApiClient = new ConcurrentBag<HttpClient>();
public HostedRepository()
{
_backendUrl = "http://localhost:56143";
}
public async Task<object> Lookup()
{
return await GetAsync<string>();
}
private async Task<T> GetAsync<T>([CallerMemberName] string request = "")
{
string uri = GetUriString(request);
var client = GetHttpClient();
using (var response = await client.GetAsync(uri))
{
ReturnHttpClient(client);
if (response.IsSuccessStatusCode)
{
var model = await response.Content.ReadAsAsync<T>();
if (model != null)
{
return model;
}
}
var err = await response.Content.ReadAsAsync<RepositoryError>();
if (err != null)
{
throw new Exception(err.Information);
}
var str = await response.Content.ReadAsStringAsync();
throw new Exception(str);
}
}
private HttpClient GetHttpClient()
{
if (!ApiClient.TryTake(out HttpClient client))
{
client = new HttpClient();
}
return client;
}
private void ReturnHttpClient(HttpClient client)
{
ApiClient.Add(client);
}
private string GetUriString(string request)
{
return $"{_backendUrl}/api/{request}";
}
}
}

View File

@@ -0,0 +1,10 @@
using System;
using System.Threading.Tasks;
namespace RepositoryLibrary
{
public interface IRepository
{
Task<object> Lookup();
}
}

View File

@@ -0,0 +1,17 @@
using SharedLibrary.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace RepositoryLibrary
{
public class LocalRepository : IRepository
{
public async Task<object> Lookup()
{
throw new RepositoryException();
}
}
}

View File

@@ -0,0 +1,15 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netcoreapp3.1</TargetFramework>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.AspNet.WebApi.Client" Version="5.2.7" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\SharedLibrary\SharedLibrary.csproj" />
</ItemGroup>
</Project>

View File

@@ -3,9 +3,13 @@ Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 16
VisualStudioVersion = 16.0.30611.23
MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "WebMVC", "WebMVC\WebMVC.csproj", "{FDAFEB96-62CA-46ED-8DC5-0D15F13CBF1B}"
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "WebMVC", "WebMVC\WebMVC.csproj", "{FDAFEB96-62CA-46ED-8DC5-0D15F13CBF1B}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ApiService", "ApiService\ApiService.csproj", "{381379E2-15DC-4835-A260-7B1E52ADE46D}"
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ApiService", "ApiService\ApiService.csproj", "{381379E2-15DC-4835-A260-7B1E52ADE46D}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "RepositoryLibrary", "RepositoryLibrary\RepositoryLibrary.csproj", "{79A0D2A7-A633-41DE-A67A-EAAA8BFD46EF}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SharedLibrary", "SharedLibrary\SharedLibrary.csproj", "{4E226D1F-35AA-4C4E-B4E5-55818F98B554}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
@@ -21,6 +25,14 @@ Global
{381379E2-15DC-4835-A260-7B1E52ADE46D}.Debug|Any CPU.Build.0 = Debug|Any CPU
{381379E2-15DC-4835-A260-7B1E52ADE46D}.Release|Any CPU.ActiveCfg = Release|Any CPU
{381379E2-15DC-4835-A260-7B1E52ADE46D}.Release|Any CPU.Build.0 = Release|Any CPU
{79A0D2A7-A633-41DE-A67A-EAAA8BFD46EF}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{79A0D2A7-A633-41DE-A67A-EAAA8BFD46EF}.Debug|Any CPU.Build.0 = Debug|Any CPU
{79A0D2A7-A633-41DE-A67A-EAAA8BFD46EF}.Release|Any CPU.ActiveCfg = Release|Any CPU
{79A0D2A7-A633-41DE-A67A-EAAA8BFD46EF}.Release|Any CPU.Build.0 = Release|Any CPU
{4E226D1F-35AA-4C4E-B4E5-55818F98B554}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{4E226D1F-35AA-4C4E-B4E5-55818F98B554}.Debug|Any CPU.Build.0 = Debug|Any CPU
{4E226D1F-35AA-4C4E-B4E5-55818F98B554}.Release|Any CPU.ActiveCfg = Release|Any CPU
{4E226D1F-35AA-4C4E-B4E5-55818F98B554}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE

View File

@@ -0,0 +1,14 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SharedLibrary.Models
{
public class RepositoryError
{
public string Information { get; set; }
public string StackTrack { get; set; }
}
}

View File

@@ -0,0 +1,13 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SharedLibrary.Models
{
public class RepositoryException : Exception
{
}
}

View File

@@ -0,0 +1,7 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netcoreapp3.1</TargetFramework>
</PropertyGroup>
</Project>

View File

@@ -1,5 +1,6 @@
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using RepositoryLibrary;
using System;
using System.Collections.Generic;
using System.Linq;
@@ -10,10 +11,21 @@ namespace WebMVC.Controllers
{
public class ApiController : Controller
{
private readonly IRepository _repository;
public ApiController(IRepository repository)
{
_repository = repository;
}
public override void OnActionExecuted(ActionExecutedContext context)
{
// This is where I capture the error from the ApiService
// This is where I capture the error from when calling the ApiService
base.OnActionExecuted(context);
}
public async Task<IActionResult> Lookup()
{
var lookup = await _repository.Lookup();
return Ok(lookup);
}
}
}

View File

@@ -5,6 +5,7 @@ using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using RepositoryLibrary;
using WebMVC.Models;
namespace WebMVC.Controllers
@@ -12,10 +13,12 @@ namespace WebMVC.Controllers
public class HomeController : Controller
{
private readonly ILogger<HomeController> _logger;
private readonly IRepository _repository;
public HomeController(ILogger<HomeController> logger)
public HomeController(ILogger<HomeController> logger, IRepository repository)
{
_logger = logger;
_repository = repository;
}
public IActionResult Index()
@@ -23,8 +26,13 @@ namespace WebMVC.Controllers
return View();
}
public IActionResult Privacy()
public async Task<IActionResult> Privacy()
{
// To get this working, I have make a call here in the Privacy page.
// Making the call in the Home/Index page was always returning a 404 Not Found.
// The second project was not starting quickly enough.
var lookup = await _repository.Lookup();
return View();
}

View File

@@ -7,6 +7,7 @@ using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using RepositoryLibrary;
namespace WebMVC
{
@@ -19,13 +20,19 @@ namespace WebMVC
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddControllersWithViews();
if (false)
{
services.AddScoped<IRepository, LocalRepository>();
}
else
{
services.AddScoped<IRepository, HostedRepository>();
}
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
@@ -39,7 +46,21 @@ namespace WebMVC
app.UseStaticFiles();
app.UseRouting();
app.Use(async (context, next) =>
{
try
{
await next();
}
catch (Exception ex)
{
// Here I want to log the exception with the StackTrace.
// The StackTrace when local is what I want
// The StackTrace when Hosted is only to the Hosted. I'd
// like to see the StackTrace returned from ApiService.
return;
}
});
app.UseAuthorization();
app.UseEndpoints(endpoints =>

View File

@@ -4,4 +4,9 @@
<TargetFramework>netcoreapp3.1</TargetFramework>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="..\RepositoryLibrary\RepositoryLibrary.csproj" />
<ProjectReference Include="..\SharedLibrary\SharedLibrary.csproj" />
</ItemGroup>
</Project>