18 ms·
Minimal APIs at a glance in .NET 6
- andix 5y agoThe old convention based model for controllers, was really difficult to understand and debug. You never knew what routes exactly were discovered by reflection. It was just too much magic, and too many conventions. I hope this will make it easier. Reminds me of the good old Nancy times.
- arethuza 5y agoWhat about attribute based routing - that makes things nice and explicit?
- silon42 5y agoStill too much magic.
- andix 5y agoIt is still some kind of reflection magic. Also most frameworks moved away from attributes and towards builders. For example entity framework or Microsoft.extensions.dependendyinjection.
- arethuza 5y agoWhat's so bad about using reflection and attributes in this context?
- andix 5y agoAttributes have to be at one specific spot (before the method/class declaration). Functions and builders you can compose. You can, for example loop, over something and add multiple routes programmatically. For example if you load the routes from a database, it’s really hard to create attributes. You would need to compile and load assemblies on the fly, or do some reflection black magic.
- arethuza 5y ago"if you load the routes from a database" Serious question (honestly not being snarky) - why would you want to do that?
- andix 5y agoI don’t know, nobody needs more the 640k of RAM, right? Maybe you have multiple modules, and depending on the configuration the routing changes. Or feature flags, that enable a breaking api change. Or a stupid customer that pays you a million dollar for custom routes. But what benefit do the attributes bring? You need to learn them by heart, on builders Intellisense can help you.
- arethuza 5y agoWell yes - if you need some kind of dynamically configurable routing then attributes aren't a good fit. I like the fact they are there right next to the relevant method...
- andix 5y agoAnother thing is, that attributes totally opinionate your code. You pull in a framework into your code. If you - for example - write one controller you want to use with multiple frameworks (ASP.NET Core or Nancy), you need one controller per framework, just for the attributes. I always found them more annoying then helpful. Most people seem to see it that way. Most frameworks are moving away from attributes for a good reason.
- aliswe 5y agoCMS:s do that! Any kind of editorial content being served is a use case.
- merb 5y agobtw. in .net core you can either use attributes or builders to create your routes or even more stuff. at least since (i think) 3.0. and if that is not a great fit you can actually build your own routing by creating a middleware (btw. the endpoint routing stuff is just a middleware)
- jayd16 5y agoProbably attributes have to be added to classes, builders can receive types through a method. If you can't change the code, you can't use attributes. Construction time is also probably the safest place to inject dependencies.
- WorldMaker 5y ago1) Startup time: reflection can take a ton of time to run. It only needs to happen once, but especially as more and more web servers move to idle models where cold startup time matter rather than just holding on to a warm service, it's not always as amortized as before. 2) AOT compilation support/size: relying on Reflection APIs means that much more metadata/symbol data has to be preserved during an AOT compilation. This impacts metadata that needs to be passed to the AOT pass and final build size from the AOT. Some web applications are interested in delivering full, streamlined AOT builds rather than typical .NET CLR applications (and JIT compilation).
- kumarvvr 5y agoMore importantly, if the default is to depend heavily on conventions, MS should have had a big glaring button / warning / notification in the Introduction page, which summarizes all the conventions used. Would have saved many beginners a lot of time. I am an experienced programmer and was very frustrated having to search for all the conventions used in the framework.
- andix 5y agoThat always drove me nuts. You need to learn all those conventions from the examples. And then you always got the strangest surprises and still needed to use attribute based routing.
- Rapzid 5y agoSomething that drives me crazy about the current ASP.NET Core documentation is that it is overly example based. I wish there were more comprehensive coverage of the subsystems.
- andix 5y agoTotally. Most of the time I don’t even check the docs, I go straight away to the source code on GitHub.
- oaiey 5y agoTrue story. We developers are an interesting species. Documentation is for us never sufficient because we want to know how the sausage is done down to the if statement. And for good reasons.
- SketchySeaBeast 5y agoAbsolutely. I've wasted hours doing things that, if I'd been shown the way Microsoft wanted me to do them, I'd solve in 10 minutes, but instead I need to spend a ton of time trying to figure out why the new variable on my model isn't binding correctly because I didn't realize they need to be properties.
- numlock86 5y agoSo basically this is expressjs for .NET.
- andix 5y agobest of both worlds
- 0xcoffee 5y agoIs there any example of how this would work with dependency injection? Or it's expected to manually call the service provider inside the lambda? Or if I just add my interfaces to the lambda parameters they will automatically resolved? edit: It supports DI using `[FromServices]` attribute! https://gist.github.com/davidfowl/ff1addd02d239d2d26f4648a06158727?WT.mc_id=-blog-scottha#explicit-parameter-binding https://gist.github.com/davidfowl/ff1addd02d239d2d26f4648a06... edit: Apparently this was in the article, but I overlooked it..
- Vake93 5y agoJust pass them as parameters for the lambda. Good Example: https://github.com/DamianEdwards/MinimalApiPlayground/blob/main/src/Todo.Dapper/Program.cs#L33 https://github.com/DamianEdwards/MinimalApiPlayground/blob/m...
- zzbzq 5y agoThe target audience for it, though, is probably us folks who want to remove dependency injection altogether. It was going against the grain before because the whole framework was built around Controllers and the part of the pipeline that had a monopoly on constructing them. With these changes it looks like it will be fully supported to write server-side HTTP code as if it were a computer program. Like you can in any other language. Better late than never!
- tonyedgecombe 5y agoThat's interesting, I've been avoiding .Net for web projects because of the DI. Time to take another look.
- ddek 5y agoSo I guess we've had 'JavaScript but like C#', in the form of TypeScript; so I suppose now we get 'C# like JavaScript'? I must admit, I find this amusing. I suppose this raises two questions: "Why use C# like this in place of express or koa on node, which idiomatically similar?", and "Why use C# like this instead of C# like that (the way all other AspNetCore apps do it)?"
- nodejs_rulez_1 5y agoThey neither broke the type system to make it weaker nor did they stick a browser engine where it doesn't belong.
- andix 5y agoYou still get C#/.NET, with it's superior performance and type safety, but just without all the OOP bloat.
- LAC-Tech 5y agoWait, you think this is not OOP? var app = WebApplication.Create(args); app.MapGet("/", () => "Hello World"); app.Run(); You're creating an object and calling methods on it..
- andix 5y agoThis is more functional. C# is an multi paradigm language. There is not a big difference between an FP module and an OOP static or single instance class.
- flohofwoe 5y agoTranslation for non-web-people: how to write a minimal web service in dotNET. I probably missed when the acronym "API" was hijacked by the web people to describe a custom web service protocol.
- ptx 5y agoI think the point is that the .NET API for writing a minimal web service is now more minimal, thanks to being designed around lambdas instead of heavy use of OOP. The web server API is just an example of this style of .NET API.
- inshadows 5y agoAlso the word "public" is missing. Cute examples, but I guess you're supposed to set up firewall for auth.
- oaiey 5y agoYou can just add auth middleware in there. This is still full fledged ASP.NET Core. They just wire it up using a different style. There is a chapter in the referenced gist about adding middleware. But I guess you more meant the example than the actual tech.
- nodejs_rulez_1 5y agoYeah, it's like 'front-end' by default means a bunch of js and html mashed together, rather than native UI.
- lghh 5y agoConsidering these are http wrappers around program A (the web service) that allows program B (a client) to interact with program A, I'd say API is the correct term for what this is.
- jameshart 5y agoIt never takes long when throwing together toy examples with these kinds of APIs to introduce a security risk: var uploads = Path.Combine(uploadsPath, file.FileName); Where file.FileName appears to be drawn from the content-disposition header of the request. MS’s own asp.net docs on file uploads say: “Use a safe file name determined by the app. Don't use a file name provided by the user or the untrusted file name of the uploaded file.” I’m always wary of APIs designed to look good in a DevRel evangelist’s presentation, to show how you can do something in ‘just a few lines of code’, when the reality is that actual applications will need to deal with a bunch more concerns anyway and this terse little API is not going to make one jot of difference to the essential complexity you’re trying to express. Whether you have a node express style server where you’re able to declare all your controller mappings in-line using lambdas, or a spring style router where controllers are in separate classes and methods makes no real difference to the fact you still have to write the controller body, and in any real application it is not going to be handling everything from request body handling to file system operations in one place anyway. At least when the controllers are all classes I can unit test them.
- deleted 5y ago[deleted]
- Zababa 5y ago> At least when the controllers are all classes I can unit test them. You can usually very easily transform lambas in function, so testing shouldn't be a problem.
- jhgb 5y agoLambas, the famous Elvish mathbread?
- jameshart 5y agoBut if I'm not writing my controllers using inline lambda syntax, but as functions in classes in a controllers directory,, what's the value of this minimal route declaration syntax over a 'heavierweight' solution that... also puts my controller declarations in methods of classes in a controllers directory?
- oaiey 5y agoIf you are interested in following an architect in the .NET team at Microsoft, follow @davidfowl. I met him once irl, and he is the most amazing person. He is the most influential architect within the .NET team at Microsoft and basically created ASP.NET Core together with Damian Edwards as PM. The non-core edition you need to search higher up the ranks ... Scott Guthrie ... boss of Azure.
- reverseblade2 5y agoI like giraffe better. https://github.com/giraffe-fsharp/Giraffe https://github.com/giraffe-fsharp/Giraffe
- pharmakom 5y agoSuave is a cleaner API in my view but Giraffe has better performance on the edges.
- nobleach 5y agoWhen I was doing F#, I loved both of these projects. I don't think we should always view ExpressJS/Sinatra (from Ruby) as "the standard", but there's also something to not having to do an hour of work before we can get endpoints serving responses.
- pharmakom 5y agoSuave can do an API server in a few lines in an F# script file - I think it’s even terser than ExpressJS, which requires a package.json.
- phillipcarter 5y agoI do too! One thing I do hope happens is Giraffe is able to use some of the newer APIs to simplify configuration. Config is generally something you stuff in a file to not look much at, but it can sometimes feel kinda hairy.
- oaiey 5y agoThis is part of a larger push to make ASP.NET Core and .NET easier for beginners. The difference between node.js + express vs. ASP.NET Core was a lot of boilerplate to return the first Hello World. Overcoming that churn is a huge problem for .NET adoption. Do not take three-line-minimal APIs as the end product for robust, safe and reliable endpoints. We all know better than trusting 3-line-presentations. As a seasoned .NET programmers I have a love-hate relationship to this new set of features (there are more!!!). The simplicity for rapid prototyping (or beginners) vs. the organized OOP template. The .NET 6 release will be very controversal. .NET will not get worse, however, a lot of (existing .NET/Java) people will complain about the new project/coding style attached to it.
- Hawxy 5y agoI've recently started using the new .NET 6 templates and honestly I don't miss the OOP boilerplate. Yes it's a bit of a shock at first, but you quickly realize that having your ASP.NET Core startup code split into two files and three functions has no real-world benefit. I'll still be using traditional controllers for my endpoints, however the syntactic sugar in C# 10 does improve the experience by reducing nesting and noise in general (file-scoped namespaces & implicit global usings). Overall I'm pretty happy with it.
- jayd16 5y ago>code split into two files and three functions You could always put multiple classes in a file if you wanted to organize that way. The new language changes just reduce nesting and boilerplate the IDE already took care of. (which isn't nothing). These framework changes to focus on lambdas is pretty nice though.
- kumarvvr 5y agoWhen it is purely about ASP.NET, getting rid of the old style Startup class is ok for me. The code is more compact, concise and less verbose. Most of the code in the startup is not touched in any meaningful sense after the initial setup.
- corpdronejuly 5y ago
- weijoi 5y agoEverything in a single file without namespaces brackets and other boilerplate. Good.
- throwaway4good 5y agoSo now that they have gotten bored copying Java Spring, they start copying Express.js?
- jf22 5y agoWhat would be the alternative? Not integrate and adopt useful features and smart paradigms that other frameworks have?
- thrower123 5y agoOn the one hand, I've been using approximately this style for defining routes for years using NancyFx. It's easy, it's explicit, it's much better than either the attribute or convention routing ASP MVC and WebApi have used. On the other, I hate how this is telescoping all the configuration and setup code into a blackbox. Any kind of real project, even minimal microservices, is going to have to deal with authentication and caching and logging and monitoring middlewares, and it's bad that these samples obfuscate the way that one would do that.
- LAC-Tech 5y agoLooking forward to this. I quite enjoyed C# but the boiler plate of ASP.NET always turned me off.
- pharmakom 5y agoShoehorning OOP into building HTTP APIs was the original sin IMO.
- bob1029 5y agoThese sort of efforts are commendable. I still don't like the state of parts of ASP.NET Core. 9/10 times I will just write my own Middleware and directly work with HttpContext. Blazor handles 99% of our former MVC concerns today, so we've basically done away with controllers.
- rattray 5y agoAs someone who isn't familiar with .NET, I wish this post had an example with a JSON request body and response.
- klaussilveira 5y agoYou can bind JSON to structs: https://gist.github.com/davidfowl/ff1addd02d239d2d26f4648a06158727#other-verbs-post-put-patch-etc https://gist.github.com/davidfowl/ff1addd02d239d2d26f4648a06... Or you can customize how it happens: https://gist.github.com/davidfowl/ff1addd02d239d2d26f4648a06158727#customizing-json-binding https://gist.github.com/davidfowl/ff1addd02d239d2d26f4648a06... As for responses: https://gist.github.com/davidfowl/ff1addd02d239d2d26f4648a06158727#json https://gist.github.com/davidfowl/ff1addd02d239d2d26f4648a06...
- DonnyV 5y agoThings start getting a little verbose with everything on 1 line thrown inside a function. app.MapGet("/todos/{id:int}", [Authorize("AdminsOnly")] (int id) => "This endpoint is for admins only"); Attributes make things cleaner with everything having its own line. Also you lose the ability to group a bunch of methods in 1 controller together under the same authentication policy.
- moogly 5y agoThere is a multitude of ways in which you could format that code: app.MapGet( "/todos/{id:int}", [Authorize("AdminsOnly")](int id) => "This endpoint is for admins only"); Or for people who don't like expression bodied members: app.MapGet( "/todos/{id:int}", [Authorize("AdminsOnly")](int id) { return "This endpoint is for admins only"); }); Extracted to a method: app.MapGet("/todos/{id:int}", GetTodos); [Authorize("AdminsOnly"] string GetTodos(int id) => "This endpoint is for admins only"; And more... You could also put these methods in a class and put the attribute on the class, which would solve your "grouping" problem.
- phillipcarter 5y agoI love this, not because of the "it's for beginners" framing, but from a "I want less boilerplate" framing. I look forward to a future .NET that gets less verbose each release, regardless of language chosen.
- ripley12 5y agoSame! Your Simple Programs proposal in that area is really great: https://github.com/dotnet/designs/pull/213 https://github.com/dotnet/designs/pull/213 I am really looking forward to the day when I can use C# for all my scripting needs instead of Bash/Python/PowerShell. We’re getting there.
- urza 5y agoNancy and Sinatra anyone? :)
- zija 5y agoI don't know what to think about it. Half-baked idea: use free functions only in one file in project is meh.. Modern Kotlin, Scala, F# can and use free functions and reduce boilerplates to minimum. C# developers wants attract newbies, juniors, fans of J's, python etc and simultaneously don't disturb old users, fans of c#/java and enterprise development. "It's only for quick scripts, prototyping, for teaching". Choose a side, don't pretend that you are modern and cool. Modern c# is fine, but some features are only sugar, and yet i still waiting for proper sum types with exhausting pattern matching. Slow progressing java have this in 17 version..
- throw868788 5y agoThe real reason is to attract and onboard people onto the platform. Part of me always felt they should of just put a functional wrapper on their APIs, have an API that avoids the mutative fluent interface, and then just show some F# examples. Especially for people outside the .NET ecosystem it would show how terse, yet performant and feature rich the platform actually is. It would compare well to examples from other langs/ecosystems. In the workplaces I've been in newer developers typically try then abandon the OO paradigm. They've seen they can get by without it and get decent performance, and there is a learning curve which experienced people have already paid for and typically then take for granted (patterns, DI, class structure, interfaces vs abstract classes, etc etc etc).