Last active
November 19, 2022 00:10
-
-
Save DamianEdwards/69a25cd21dff567f40c74ddd4fd43921 to your computer and use it in GitHub Desktop.
Example ASP.NET Core Razor Page in C# that calls a quotes REST API with fallback to offline quotes in case of failure
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@page | |
@model IndexModel | |
@{ | |
ViewData["Title"] = "Home page"; | |
<div class="card"> | |
<div class="card-body"> | |
@await Model.GetInspirationalQuote() | |
</div> | |
<div class="card-footer"> | |
<form method="get"> | |
<button class="btn btn-primary btn-sm" type="submit">Get New Quote</button> | |
</form> | |
</div> | |
</div> | |
} | |
<div class="text-center"> | |
<h1 class="display-4">Welcome</h1> | |
<p>Learn about <a href="https://docs.microsoft.com/aspnet/core">building Web apps with ASP.NET Core</a>.</p> | |
</div> |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System.Diagnostics; | |
using Microsoft.AspNetCore.Mvc.RazorPages; | |
namespace WebApplication108.Pages; | |
public class IndexModel : PageModel | |
{ | |
private readonly ILogger<IndexModel> _logger; | |
private readonly HttpClient _httpClient; | |
public IndexModel(ILogger<IndexModel> logger, IHttpClientFactory httpClientFactory) | |
{ | |
_logger = logger; | |
_httpClient = httpClientFactory.CreateClient("quotes.api"); | |
} | |
public void OnGet() | |
{ | |
} | |
private static List<string> _backupQuotes = new() | |
{ | |
"The determination to win is the better part of winning.", | |
"if ( socialDistancing.isOver() ){\n\tpeople.hug();\n}", | |
"await sign" | |
// Add more backup quotes here | |
}; | |
private static string GetBackupQuote() | |
{ | |
var index = Random.Shared.Next(_backupQuotes.Count - 1); | |
return _backupQuotes[index]; | |
} | |
public async Task<string> GetInspirationalQuote() | |
{ | |
const string apiPath = "quote"; | |
try | |
{ | |
var sw = new Stopwatch(); | |
var quote = await _httpClient.GetFromJsonAsync<QuoteResult>(apiPath); | |
sw.Stop(); | |
if (_logger.IsEnabled(LogLevel.Information)) | |
{ | |
_logger.LogInformation("Call to {url} took {apiResponseTime}", new Uri(_httpClient.BaseAddress!, apiPath), sw.Elapsed); | |
} | |
return quote?.Quote ?? GetBackupQuote(); | |
} | |
catch (Exception ex) | |
{ | |
// There was an error calling the API, fallback to offline/backup quotes | |
if (_logger.IsEnabled(LogLevel.Error)) | |
{ | |
_logger.LogError(ex, "Error calling quote of the day API at {url}: {errorMessage}", new Uri(_httpClient.BaseAddress!, apiPath), ex.Message); | |
} | |
return GetBackupQuote(); | |
} | |
} | |
public class QuoteResult | |
{ | |
public string? Quote { get; init; } | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var builder = WebApplication.CreateBuilder(args); | |
// Add services to the container. | |
builder.Services.AddRazorPages(); | |
builder.Services.AddHttpClient("quotes.api", http => | |
{ | |
// Get API key from appropriate place, e.g. user secrets in dev, environment variable in prod, etc. | |
//var apiKey = builder.Configuration["QuotesApi:ApiKey"]; | |
//http.DefaultRequestHeaders.Add("X-API-Key", apiKey); | |
// Add any other required headers | |
// Set base address | |
http.BaseAddress = new Uri("https://nodejs-quoteapp.herokuapp.com/"); | |
}); | |
var app = builder.Build(); | |
// Configure the HTTP request pipeline. | |
if (!app.Environment.IsDevelopment()) | |
{ | |
app.UseExceptionHandler("/Error"); | |
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts. | |
app.UseHsts(); | |
} | |
app.UseHttpsRedirection(); | |
app.UseStaticFiles(); | |
app.UseRouting(); | |
app.UseAuthorization(); | |
app.MapRazorPages(); | |
app.Run(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment