Skip to content

Instantly share code, notes, and snippets.

View emrekizildas's full-sized avatar
🎯
Focusing

Emre Kızıldaş emrekizildas

🎯
Focusing
View GitHub Profile
public class TypedClientModel : PageModel
{
private readonly ExampleService _exampleService;
public IEnumerable<User> Users { get; private set; }
public bool HasUser => Users.Any();
public bool GetUsersError { get; private set; }
services.AddHttpClient<ExampleService>();
public class ExampleService
{
public HttpClient Client { get; }
public ExampleService(HttpClient client)
{
client.BaseAddress = new Uri("https://api.example.com/");
client.DefaultRequestHeaders.Add("Accept","application/json");
client.DefaultRequestHeaders.Add("User-Agent","HttpClientFactory-Sample");
Client = client;
public class NamedClientModel : PageModel
{
private readonly IHttpClientFactory _clientFactory;
public IEnumerable<Employee> Employees { get; private set; }
public bool GetEmployeesError { get; private set; }
public bool HasEmployees => Employees.Any();
services.AddHttpClient("example", c =>
{
c.BaseAddress = new Uri("https://api.example.com/");
c.DefaultRequestHeaders.Add("Accept", "application/json");
c.DefaultRequestHeaders.Add("User-Agent", "HttpClientFactory-Sample");
});
public class FirstUsageModel : PageModel
{
private readonly IHttpClientFactory _clientFactory;
public IEnumerable<User> Users { get; private set; }
public bool GetUsersError { get; private set; }
public BasicUsageModel(IHttpClientFactory clientFactory)
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
public void ConfigureServices(IServiceCollection services)
@using CSPExample.Helper
@{
ViewData["Title"] = "Home Page";
}
<div class="text-center">
<h1 class="display-4">Welcome</h1>
<p>Learn about <a href="#" id="click">building Web apps with ASP.NET Core</a>.</p>
</div>
using Microsoft.AspNetCore.Html;
using Microsoft.AspNetCore.Mvc.Rendering;
namespace CSPExample.Helper
{
public static class NonceHelper
{
public static HtmlString Nonce(this IHtmlHelper helper)
{
string nonceValue = helper.ViewContext.HttpContext.Items["ScriptNonce"].ToString();
app.Use((context, next) =>
{
var rng = new RNGCryptoServiceProvider();
var nonceBytes = new byte[32];
rng.GetBytes(nonceBytes);
var nonce = Convert.ToBase64String(nonceBytes);
context.Items.Add("ScriptNonce", nonce);
context.Response.Headers.Add("Content-Security-Policy",
new[] { string.Format("script-src 'self' 'nonce-{0}'", nonce) });
return next();