-
Notifications
You must be signed in to change notification settings - Fork 10.2k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
HttpContext and JSON #17160
Comments
Not a fan of adding any more stuff directly on HttpRequest. HasFormContentType mainly makes sense because Form is also there, and in hindsight neither should have been. When all of the other new JSON APIs are extensions, HasJsonContentType might as well be too. |
I think either one of these could be reasonable, I went back and forth on which one to propose. It accomplishes the same goal either way, just slightly inconsistent in terms of syntax. |
While I agree it would be ideal to not add more virtuals like this to the HttpContext, extension methods for things like this aren't great. Would we still do this if we add the Try methods? |
Why the |
The HttpResponse is write only. You can read the body if you replace the output stream with a readable stream (like a memory stream or something more efficient...) |
I did it in this way and not sure it's efficient. Could you show me similar internal usage of reading HttpResponse in ASP.NET Core? |
In the second-to-last example, isn’t that mixing up Content-Type and Accept? |
Request content type check
seems a little bit painful to write to each endpoint. Extension methods target But I was asking myself if imperative involved low level. For example attach the extension methods to
|
This looks really good and useful! Will it be possible to use together with dependency injection in an easy way in a library for example? Also without resolving the whole huge business implementation that I might have in a single huge ctor for all mappings. The only examples I found did this in the Configure() method. |
Wouldn't break that the ability though to use different serializers like Json.NET with MVC? That would be a huge breaking change for anyone that relies on the ability to switch to a serializer with a larger feature set. Wouldn't it make more sense to use the existing abstractions that exist, to allow users to have the choice? |
Rather than coupling these methods to the HTTP request and response objects, couldn't they be targeting the PipeReader/PipeWriter or other abstraction for the request/response bodies? After all, that's what is actually being read/written. These may be more generally useful beyond HttpContext. |
How would this play with model validation? Will there be a way of getting a hold of the model validation system through DI? |
Important scenario: Reading and writing JSON DOM. Think of JObject and JArray from Json.NET, but with the new JSON DOM: endpoints.MapPost("/weather", async context =>
{
var weather = await context.Request.ReadJsonAsync<JsonObject>();
await UpdateDatabase(weather["id"], weather["state"]);
context.Response.StatusCode = StatusCodes.Status202Accepted;
}); Hopefully System.Text.Json.JsonSerializer will Just Work when given one of these JSON DOM objects, but it is worth double checking with the JSON crew. |
At risk of starting a bikeshedding sesh, the methods on
Serialize/Deserialize would be more consistent with |
They should be on the request and response. There's already and API to read from a Stream but not a PipeReader and PipeWriter). If those get added, they should be in corefx, not in ASP.NET Core. The other reason I prefer them on the HttpRequest and HttpResponse is that it allows us to change the implementation (from Stream to PipeReader) and not break consuming code. |
We could do another study 😄 , I still prefer Read/Write since those are the verbs we use today https://docs.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.mvc.formatters.inputformatter?view=aspnetcore-3.0 |
Which abstractions? Anything that exists today live in the wrong layer in the stack. That's another challenge. We don't want to push those things (which have the wrong namespace) lower into the core abstractions. That said, @rynowak what would it look like if we added an abstraction (even if it lives in corefx)? |
I think it should be on the request and response, not HttpContext (we don't have much on the HttpContext today). That code sample does make me lean towards the Try* API more though. |
Are you asking specifically about injecting services into those routing delegates? |
No one uses inputters/outputters directly. I don't think we should pay them any attention. More interesting prior art is |
And ReadFormAsync as @rynowak mentioned. |
public static ValueTask WriteJsonAsync(
this HttpResponse response,
Type type,
object? value,
CancellationToken cancellationToken = default) { throw null; } What does the |
Your usage is adequate but will have issues with larger responses. The main optimization we make in our own components is to do what we call write-through processing. The bytes are processed as they're written rather than copied back at the end. |
It does if you bring into context the |
If you want to use DI it is really not a god option to not use DI. And injecting a IServiceCollection or some other factory method is not a compelling solution at all. Then I rather go with som other pattern like pure MVC or something else. |
Not sure what you mean, you don't have to use DI if you don't want, but you can't really use closures (or I'm misunderstanding what you mean). Consider the following: endpoints.MapPost("/weather/{id}", async context =>
{
var id = context.Request.RouteValues["id"];
var weather = await context.Request.ReadJsonAsync<JsonObject>();
using var db = new WeatherContext();
var w = db.Weathers.Find(int.Parse(id));
w.State = weather.State;
await db.SaveChangesAsync();
context.Response.StatusCode = StatusCodes.Status202Accepted;
}); Now you want to inject the WeatherContext so this can be tested. Here are some options: Task PostWeather(HttpContext context, WeatherContext db)
{
var id = context.Request.RouteValues["id"];
var weather = await context.Request.ReadJsonAsync<JsonObject>();
var w = db.Weathers.Find(int.Parse(id));
w.State = weather.State;
await db.SaveChangesAsync();
context.Response.StatusCode = StatusCodes.Status202Accepted;
}
// 1.
endpoints.MapPost("/weather/{id}", async context =>
{
using var db = new WeatherContext();
await PostWeather(context, db);
});
// 2.
endpoints.MapPost("/weather/{id}", async context =>
{
// Scoped service
var db = context.RequestServices.GetRequiredService<WeatherContext>();
await PostWeather(context, db);
});
// 3. We could add overloads that make this easier
endpoints.MapPost("/weather/{id}", async (HttpContext context, WeatherContext db) =>
{
// Scoped service
await PostWeather(context, db);
}); |
@davidfowl -- Sorry for the confusion. I should've been more specific, clear and accurate. I only meant to imply that developer's don't always HAVE to jump right into the built-in IoC container. And that dependencies could be provided by others means, in (my opinion) sometimes a more explicit way. Either using closures, or a plain old object. For example: using System;
using System.Data;
using System.Data.SQLite;
using System.Net;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Routing;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
namespace WebApp {
public class Program {
public static async Task<int> Main(string[] args) {
try {
var db = new Db("Data Source=:memory:;Version=3;New=True;");
var server = new Server(db);
var host = new WebHostBuilder()
.UseKestrel()
.UseUrls("http://localhost:5000/;https://localhost:5001")
.ConfigureServices(_configureServices)
.Configure(_configure(server))
.Build();
await host.RunAsync();
return 0;
} catch {
return -1;
}
}
static void _configureServices(IServiceCollection services) {
services.AddRouting();
}
static Action<WebHostBuilderContext, IApplicationBuilder> _configure(Server server) {
return (context, app) => {
app.UseRouting();
app.UseEndpoints(server.Routes);
app.Run(server.handleNotFound);
};
}
}
internal class Server {
readonly Db _db;
internal Server(Db db) {
_db = db;
}
internal void Routes(IEndpointRouteBuilder r) {
r.MapGet("/post/get", handlePostGet);
r.MapGet("/hello/{name}", handleHelloName);
r.MapGet("/", handleHello);
}
internal Task handleNotFound(HttpContext ctx) {
ctx.Response.StatusCode = (int)HttpStatusCode.NotFound;
return ctx.Response.WriteAsync("Post not found.");
}
Task handleHello(HttpContext ctx) =>
ctx.Response.WriteAsync("Hello World!");
Task handleHelloName(HttpContext ctx) =>
ctx.Response.WriteAsync("hello " + ctx.Request.RouteValues["name"]);
Task handlePostGet(HttpContext ctx) {
using var conn = _db.CreateConnection();
using var cmd = conn.CreateCommand();
cmd.CommandText = "SELECT 1 as post_id, 'hello world' as title, 'some text' as body";
using var rd = cmd.ExecuteReader();
if (rd.Read()) {
return ctx.Response.WriteAsync(rd.GetString(rd.GetOrdinal("body")));
} else {
return handleNotFound(ctx);
}
}
}
internal class Db {
readonly string _connStr;
internal Db(string connStr) {
_connStr = connStr ?? throw new ArgumentNullException(nameof(connStr));
}
internal IDbConnection CreateConnection() =>
new SQLiteConnection(_connStr).OpenAndReturn();
}
} This example is trivial, uses poor naming (I did this for simplicity) and missing a bunch of boilerplate code (null dep checks, error checking etc.), but demonstrates the point I'm trying to make. This approach I think is testable and clear. I also like that I could be missing something glaring, I definitely don't have a CS background. For whatever that's worth. As someone who came from outside .NET, I wish the approach in teaching the platform started from this perspective. As opposed to "here is full-blown MVC and EF". I believe that we'd like have greater adoption, and probably better developer's. Just my two uneducated cents. p.s. @davidfowl loving the lack of braces on those usings? |
Sorry if it feels like I'm bike-shedding here - but in the example, it's a GET and the parameter is via the route, so I'm unclear why you'd care what the Content-Type is? It's fine to explicitly avoid the content-negotiation dance, but the proposed API changes seem to assume that checking Content-Type is the same as checking Accept |
I feel now that I was a bit to hard in my response, I strongly agree with you that it's great to have both options! Thad adds a lot of value to the stack! |
@pimbrouwers In your example, the Db class is a singleton. That's why I said closures don't work for all scenarios. If you want things created per request and you want to be able to pass them explicitly, you're kinda stuck with the IoC container or code is that creating objects per request (like a factory or using new) |
Ah! Thats the mistake. I'll fix the example, thanks! |
That feels the best option. The default options as you said are sub-optimal (my standard is: camelCase properties, camelCase enums, omit null properties) so there is a need for an easy way to change the options, in a single place for everything (uncommon to have different options per endpoint).
I think it would be nice to have a way to specify globally a media type, like the options, as it is not uncommon to use same custom media type and serialization options for all endpoints.
It's not clear to me if this would only handle the Anyway, if this is going to happen, and there is going to be a default media type (as per above comment), then there should probably be a method to enforce the default like I really like this as I think it would be really useful to write simple endpoints. What about having some standard exceptions that can be thrown by this methods and handled by default, so you can either:
e.g.
|
@JamesNK - updated with our notes |
You know the other place people have been begging us to add these json extensions? Session. Our docs even have a basic version of them you can paste into your app. |
API approved - we've made some small edits:
Also, it looks like IdentityServer has already done the work to make their extensions scoped: IdentityServer/IdentityServer4#3699 |
@JamesNK Can you get to this in preview6? |
HttpContext and JSON
This is a proposal to add extension methods for using
HttpContext
(and related types) withSystem.Text.Json
. Adding this functionality will make ASP.NET Core developers productive with smaller amounts of code. This is aligned with our goal of making route-to-code a useful programming pattern.Goals
Make this the easiest imperative way to read/write JSON
Make this fastest way to read/write JSON
Do HTTP things correct by default (don't cut corners)
Replace the guts of MVC's JSON formatter with this (validates flexibility)
Do all of this without requiring service registration/configuration
NON-GOAL: Create an abstraction for JSON serializers/settings
API Additions
These are the proposed APIs, see the following (annotated) sections for discussion.
Some updates based on recent discussions with @JamesNK and @Tratcher:
Microsoft.AspNetCore.Http.Extensions
assembly.JsonOptions
would be inherited (used as the base) by MVC and SignalR - but they are copies. So modifyingJsonOptions
would influence MVC and SignalR - but not the reverse. This is worth a discussion.contentType
should specify the value they want to see in theContent-Type
header. We will not append a charset. We will not parse the value you give us and change the encoding based on charset. It's your job to get it right.Design Notes
0: General Shape
There are three primary APIs here:
TValue
)Type type
)TValue value
)Type type, object value
)In general I've tried to keep naming consistent with the functionality for reading the form (
HasFormContentType
,ReadFormAsync()
).1: HasJsonContentType
I tried to make the design of this similar to
HasFormContentType
which already exists on theHttpRequest
. I considered as well making this an extension method, but there's no good reason to deviate from the pattern we established with form.There's nothing about this property that makes it specific to a serializer, it's a straightforward comparison of the content type.
2: Namespace
One of the challenges in this area is that if we park the best method names to mean
System.Text.Json
, then this will be confusing to someone using another serializer. It would be really annoying to use JIL and seeReadJsonAsync()
show up everywhere, but meanSystem.Text.Json
. For this reason I put these extensions in a different namespace.You could imagine that another serializer would want to provide similar functionality. I want to make sure the existing serializer ecosystem can coexist with this addition.
In my mind there are a few ways to address this challenge:
System.Text.Json
in the method namesCreating a serializer abstraction has a bunch of problems:
JsonSerializerOptions
from the APIsI reject this option, I think it defeats enough of our stated goals.
Considering other options - the namespace seems like the best, most flexible choice. Putting
System.Text.Json
in the names would be flexible as well, but would be ugly. So I'm pitching the namespace.I think any of the non-abstraction options would be reasonable for us to choose while still meeting our goals.
3: ReadJsonAsync and Overload Set
I took the approach of defining lots of overloads here with just the cancellation token as an optional parameter.
The reason why is because of what happens when you using cancellation tokens with other optional parameters. Imagine that I made a single overload with optional parameters for both options and cancellation token.
We can avoid this ugliness by defining more overloads.
4: Media Type and Encoding
There are a lot of overloads of
WriteJsonAsync
- I'm interested in ways to cut this down.We need to expose the media type as an option because it's becoming more common to use suffix content types like
application/cloud-events+json
. This fills a gap in what traditional media types do - a media type likeapplication/json
describes a data-representation, but says nothing about the kind of data being represented. More modern designs like CloudEvents will use suffix content types to describe both.We need to expose the encoding because we MVC supports it (it's a goal to have MVC call this API), and because we still have the requirement to support things like
GB2312
.I don't think either of these things are contraversial, we should debate whether we're happy with the design being proposed here as the best way to express this flexibility.
5: Managing JsonSerializerOptions
We need a strategy to deal with the fact that the default settings of
JsonSerializerOptions
are bad for the web. We want the serializer to output camelCase JSON by default, and be more tolerant of casing differences on input. Also because we know that we're always outputting text with a character encoding, we can be more relaxed about the set of characters we escape compared to the defaults.I reject the idea that we'd give the user the default
JsonSerializerOptions
through these APIs and make it their job to manage, because that conflicts with the goal of this being the easiest way to do JSON - we want these APIs to have good defaults for the web.There's a couple of options for how we could implement this:
Each of these have a downside. The static is a static, the downside is that its static. Using a feature either allocates a bunch or has wierd coupling (kestrel coupled to a serializer). Using options has some runtime overhead for the service lookup. Of these options seems like the best choice. We could also use the options approach to share the options instance between MVC's JsonOptions and this one for compatibility.
Behavious
HasJsonContentType
This method will return true when a request has a JSON content type, that is:
Null or empty content type is not considered a match.
ReadJsonAsync
The overloads of
ReadJsonAsync
will throw an exception if the request does not have a JSON content type (similar toReadFormAsync
).Depending on the value of
CharSet
the method may need to create a stream to wrap the request body and transcode -System.Text.Json
only speaks UTF8. We're in discussions with CoreFx about moving our transcoding stream implementations into the BCL. We will assume UTF8 if noCharSet
was provided, the serializer/reader will validate the correctness of the bytes.We'll call the appropriate overload of
JsonSerializer.DeserializeAsync
to do the heavy lifting.There's a couple of usability concerns here related to error handling. These APIs optimize for the happy path:
Someone who wants to handle both of these errors and turn them into a 400 would need to write an
if
for the content type, and atry
/catch
for the possible exceptions from deserialization.It would be possible to make a
TryXyz
set of APIs as well - they would end up handling the exception for you. Since these are extension methods, they can't really log (without service locator).With a union:
A possibly better version:
WriteJsonAsync
Prior to doing the serialization to the response body, the
WriteJsonAsync
method will write a content type (withCharSet
) to theContent-Type
header. If no content type is specified thenapplication/json
will be used. If no encoding is specified, then UTF8 will be used.Serialization will call
JsonSerializer.SerializeAsync
- and provide a wrapper stream if an encoding other than UTF8 is in use.Code Samples
Reading JSON from the request.
Writing JSON to the response.
Writing JSON to the response with explicit content type.
I'm not completely in love with this one. We might want to think about making more parameters optional.
Explicitly handling bad content-type
Letting routing handle bad content-type (possible feature)
The text was updated successfully, but these errors were encountered: