dotnet / aspnetcore.docs.samples Goto Github PK
View Code? Open in Web Editor NEWLicense: Creative Commons Attribution 4.0 International
License: Creative Commons Attribution 4.0 International
Hello everyone!
I've been delving into the Identity Documentation, particularly the sections covering 2FA with Razor Pages, and it's been an enlightening experience!
However, I'm currently facing a gap in documentation when it comes to integrating 2FA with Single Page Applications (SPAs).
Would it be possible to provide a comprehensive example for 2FA with ASP.NET Core Identity and Angular? I'm specifically interested in understanding how to leverage endpoints for seamless SPA integration. Unfortunately, I couldn't find any information related to 2FA TOTP in the Angular Sample.
This addition would immensely benefit developers looking for a thorough guide on 2FA integration with Angular. Your efforts in this regard would be highly appreciated! Thank you!
See https://devblogs.microsoft.com/dotnet/asp-net-core-updates-in-net-7-preview-1/
Put in https://github.com/dotnet/AspNetCore.Docs.Samples/tree/main/fundamentals/minimal-apis/samples/IFormFile
var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();
app.MapGet("/", () => "Hello World!");
app.MapPost("/fileUp", async (IFormFile file) =>
{
string tempfile = Path.GetTempFileName();
using var stream = File.OpenWrite(tempfile);
await file.CopyToAsync(stream);
});
app.MapPost("/FilesUp", async (IFormFileCollection myFiles) =>
{
foreach (var file in myFiles)
{
string tempfile = Path.GetTempFileName();
using var stream = File.OpenWrite(tempfile);
await file.CopyToAsync(stream);
}
});
app.Run();
Update readme.txt with instructions on testing.
Hi,
While looking over the reate limitter documentatin I was looking at the following code sample:
_.OnRejected = (context, _) =>
{
if (context.Lease.TryGetMetadata(MetadataName.RetryAfter, out var retryAfter))
{
context.HttpContext.Response.Headers.RetryAfter =
((int) retryAfter.TotalSeconds).ToString(NumberFormatInfo.InvariantInfo);
}
context.HttpContext.Response.StatusCode = StatusCodes.Status429TooManyRequests;
context.HttpContext.Response.WriteAsync("Too many requests. Please try again later.");
return new ValueTask();
};
Is the WriteAsync
method call missing the await
by design? At first glance this seems as a bug.
As dotnet test tool suggests, this ref is only needed in .NET Core projects, but not in .NET 7
Return multiple result types from minimal APIs
Possibly same code can do #76
See Antiforgery integration for minimal APIs
and this sample
In this code I pass in the action so
app.MapGet("/DisableAntiforgery", () =>
{
return Results.Content(MyHtml.html("/todo"), "text/html");
});
app.MapGet("/post2", () =>
{
return Results.Content(MyHtml.html("/todo2"), "text/html");
});
Can use the same HTML when they pass in the action arg.
Is there a clean way to do this to pass in an arg for
<input name="{token.FormFieldName}"
type="hidden" value="{token.RequestToken}" />
Maybe that makes things too messy. Perhaps I should duplicate most of the HTML and not get the HTML from a method while passing the action.
public static string html2(string action, AntiforgeryTokenSet token) => $"""
<html><body>
<form action="{action}" method="POST" enctype="multipart/form-data">
<input name="{token.FormFieldName}"
type="hidden" value="{token.RequestToken}" />
<input type="text" name="name" />
<input type="date" name="dueDate" />
<input type="checkbox" name="isCompleted" />
<input type="submit" />
</form>
</body></html>
""";
Works, but I'm not sure it's an improvement. There's no way to pass in a null token.
cc @guardrex
Create sample code. See https://devblogs.microsoft.com/dotnet/asp-net-core-updates-in-dotnet-7-preview-4/
Possibly same code can do dotnet/sdk#77
ASP.NET Core streaming sample to be cross platform. See this comment
@logiclrd do you have an ETA for that?
An example of how to use the new identity API with a standalone Blazor WebAssembly app.
Need dedicated sample for Route groups with MapGroup
@sammychinedu2ky can you create a PR here with your code from dotnet/AspNetCore.Docs#26476 so we have code dedicated to route groups. I think maintaining the same code for testing and routegroups might be a problem.
Create a folder routeGroups
under https://github.com/dotnet/AspNetCore.Docs.Samples/tree/main/fundamentals/minimal-apis/samples
See Improved support for custom authorization policies with IAuthorizationRequirementData
ToDo:
See the project here
curl -i -H "Authorization: Bearer <token>" http://localhost:{port}/api/greetings/hello
Output shows:
Evaluating authorization requirement for age >= 16
info: MinimumAgeAuthorizationHandler[0]
Minimum age authorization requirement 16 satisfied
But request returns a 415 error.
@kevinchalet can you help? CC @jxwaters if you can help
contributes to dotnet/AspNetCore.Docs#29291
See the note just above Test app prerequisites
When creating a test project for an app, separate the unit tests from the integration tests into different projects. This helps ensure that infrastructure testing components aren't accidentally included in the unit tests. Separation of unit and integration tests also allows control over which set of tests are run.
@fiyazbinhasan can you split out your integration and unit tests?
Trying to avoid horizontal scroll bars in the rendered articles.
See Typed results for minimal APIs
It would be great to have the sample from that blog here. You can get the starter project code from https://github.com/dotnet/AspNetCore.Docs/tree/main/aspnetcore/tutorials/first-web-api/samples/6.0/TodoApi
Create your new project in a new folder typed-results
under https://github.com/dotnet/AspNetCore.Docs.Samples/tree/main/fundamentals/minimal-apis/samples
See tests in https://github.com/dotnet/aspnetcore/tree/main/src/Mvc/Mvc.ApiExplorer/test
cc @sammychinedu2ky if you're interested.
@brunolins16
is the expert on this. See dotnet/aspnetcore#40656
Rate limiting middleware improvements
[EnableRateLimitingAttribute("MyControllerPolicy")]
to Home2Controller
builder.Services.AddRateLimiter(options =>
{
options.AddTokenBucketLimiter("MyControllerPolicy", options =>
{
options.TokenLimit = 1;
options.QueueProcessingOrder = QueueProcessingOrder.OldestFirst;
options.QueueLimit = 1;
options.ReplenishmentPeriod = TimeSpan.FromSeconds(10);
options.TokensPerPeriod = 1;
})
.AddPolicy<string>("MyGroupPolicy", new MyRateLimiterPolicy());
});
Then @Rick-Anderson can update Rate limiting middleware in ASP.NET Core
@Kahbazi can you do these updates?
Also, the updates requested in #14
Add options.RejectionStatusCode = StatusCodes.Status429TooManyRequests;
to JWT sample
@Kahbazi can you PR that?
Trying to do the Arrangement based on IndexPageTests.cs but a failure came and said that no such table.
Until
db.Database.EnsureCreated();
was added in a line before
Utilities.ReinitializeDbForTests(db);
So it's look like this
db.Database.EnsureCreated();
Utilities.ReinitializeDbForTests(db);
I am wondering, why is it necessary
Consider the following code:
using Microsoft.AspNetCore.RateLimiting;
using System.Threading.RateLimiting;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddRateLimiter(_ => _
.AddFixedWindowLimiter(policyName: "fixed", options =>
{
options.PermitLimit = 4;
options.Window = TimeSpan.FromSeconds(120);
options.QueueProcessingOrder = QueueProcessingOrder.OldestFirst;
options.QueueLimit = 2;
}));
var app = builder.Build();
app.UseRateLimiter();
static string GetTicks() => (DateTime.Now.Ticks & 0x11111).ToString("00000");
app.MapGet("/", () => Results.Ok($"Hello {GetTicks()}"))
.RequireRateLimiting("fixed");
app.Run();
Browse to /
on localhost and quickly hit refresh multiple times. After the rate limit is hit, the browser doesn't show a problem, it's displaying the last response. F12 tools don't show any thing and there is nothing in the log.
@wtgodbe how can the client be notified? What's the best way to log this? Why isn't the default rejection status 503 returned?
cc @fiyazbinhasan
Could you please provide the license information for your examples? We are uncertain which license applies to the examples and would appreciate it if you could add the relevant license information to the repository. Additionally, we would like to confirm if it is permissible to use the examples (e.g. test/integration-tests/IntegrationTestsSample) in our own public repository. Thank you.
See the middleware version
/api/values/Squareroot/-1
returns the generic type and title
{"type":"https://tools.ietf.org/html/rfc7231#section-6.5.1","title":"Bad Request",
not the type and title that's set
{"type":"https://en.wikipedia.org/wiki/Square_root","title":"Wrong Input"
When I Customize problem details with CustomizeProblemDetails see also source code
the API controller returns the correct problem details.
When I step through the middleware version in the debugger, everything is set correctly.
fundamentals/minimal-apis/samples/IResultImplementation/Tests/IResultImplementationTest.cs
The examples given for the integration test work perfectly and I thank you for this.
However, I've been banging my head to get it to work with the frameworks healthcheck functionality. I want to use it to test my healthchecks endpoints.
var connectionstring = "";
builder.Services.AddHealthChecks()
.AddTypeActivatedCheck<SqlHealthCheck>("SQL HealthCheck",
args: new object[] {HealthCheckSeverityKeys.Critical, connectionstring},
tags: new[] { "healthcheck" },
failureStatus:Microsoft.Extensions.Diagnostics.HealthChecks.HealthStatus.Unhealthy);
var app = builder.Build();
app.MapHealthChecks("/health", new HealthCheckOptions
{
ResponseWriter = HealthReportConverter.CustomResponseWriter,
Predicate = (check) => check.Tags.Contains("healthcheck")
});
app.Run();
The healthchecks work perfactly, but whenever trying to test these using the basic http test I do get 503 service unavailable.
In MinApiTestsSample, create at least one sample that uses the IResult
implementation types are now publicly available from Improved unit testability for minimal route handlers
@brunolins16 dotnet/aspnetcore#40965 mentions all these <HTTP Status>HttpResult
mentioned in the blog, but they're no longer in the source and I can't find a PR where they were renamed. The history of Results.cs doesn't make the renaming obvious. Please advise.
Update the model:
public class Contact
{
public int Id { get; set; }
public string Name { get; set; } = String.Empty;
public string ShortName { get; set; } = String.Empty;
public string Email { get; set; } = String.Empty;
public string PhoneNumber { get; set; } = String.Empty;
}
Then have a validation check like:
if (Contact.Name == Contact.ShortName) {
ModelState.AddModelError(nameof(Contact.ShortName),
"Short name can't be the same as Name.");
}
Code at https://github.com/dotnet/AspNetCore.Docs.Samples/tree/main/mvc/models/ModelStateError
It's easier to delete the existing code and create a new project and scaffold it.
Bonus points if you move from MVC to Razor Pages.
โ Do not edit this section. It is required for learn.microsoft.com โ GitHub issue linking.
Write sample in https://github.com/dotnet/AspNetCore.Docs.Samples/tree/main/fundamentals/minimal-apis/samples/openApi (create folder openApi)
See the sentence just above this link
The EF-Core in-memory database provider can be used for limited and basic testing, however the SQLite provider is the recommended choice for in-memory testing.
Use a service per #13 (comment)
Put the code in this folder and delete the readme.md
.
Change this line to
public static async Task<Ok<Todo[]>> GetAllTodos(TodoGroupDbContext database)
{
var todos = await database.Todos.ToArrayAsync();
return TypedResults.Ok(todos);
}
and changed test that uses that endpoint
Related to dotnet/AspNetCore.Docs#28850
rewritten test must include test of returned result type
/ Assert: Check the returned result type is correct
Assert.IsType<Ok<Todo[]>>(result);
IProblemDetailsWriter
from problem details response
In https://github.com/dotnet/AspNetCore.Docs.Samples/tree/main/fundamentals/middleware/problem-details-service or write a new sample in https://github.com/dotnet/AspNetCore.Docs.Samples/tree/main/fundamentals/middleware
Create sample that generates a problem details response from middleware:
@sammychinedu2ky are you interested in this?
In https://github.com/dotnet/AspNetCore.Docs.Samples/tree/main/mvc/models folder
Use in memory DB.
also show how to add a model error to the model, not the property:
ModelState.AddModelError(string.Empty, "My error message");
See this comment
[JsonSerializable(typeof(Todo[]))]
internal partial class AppJsonSerializerContext : JsonSerializerContext
And more can likely be removed from many of these samples
Problem details code returns
{"type":"https://wikipedia.org/wiki/Division_by_zero",
"title":"Wrong Input",
"status":404,
"detail":"Divison by zero is not defined."}
When there is no endpoint rather than just 404.
@sammychinedu2ky fixed that by adding HasPath
, but that's an error prone solution.
@brunolins16 can you suggest a better mechanism to detect when there's no matching endpoint?
EXPOSE
instructions should have the following characteristics:
Ideally, we wouldn't need to use EXPOSE
at all, but I'm guessing that VS Code relies on it.
https://github.com/search?q=repo%3Adotnet%2FAspNetCore.Docs.Samples%20EXPOSE&type=code
FYI for .NET 8: dotnet/core#8133 (comment)
A declarative, efficient, and flexible JavaScript library for building user interfaces.
๐ Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. ๐๐๐
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google โค๏ธ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.