C
C#2mo ago
Angius

Getting route data from a WebAPI without Swagger

The way I'm currently generating TS clients, is I use NSwag to get the OpenAPI spec, then I have a tool written in JS that parses that json and generates TS clients. I was thinking of eliminating some steps from that, though. The way I see it, I should be able to make a console app that references my WebAPI project, and somehow get the route data from there. All nicely typed and all. Bypassing Swagger completely. Can't figure out how, though
9 Replies
mg
mg2mo ago
Could look through NSwag's source to see how it generates the OpenAPI spec?
Angius
Angius2mo ago
Huh, good idea, didn't think of that Yeah that's not happening, NSWag is spread actoss like 70 different projects, I ain't tracking down what does the route infor gathering lol Maybe Swashbuckle is simpler...
mg
mg2mo ago
oof yeah i looked at swashbuckle and it seemed simpler
Joschi
Joschi2mo ago
If you don't use minimal APIs you could maybe use Roslyn and scan the assembly for all [Route] attributes.
Angius
Angius2mo ago
Or for [Http...] ones, another good idea, thanks
Joschi
Joschi2mo ago
You would probably need to look for the Controller and then work your way down and check each method. But Roslyn would also give you direct access to all the parameters and other attributes for return typing.
ffmpeg -i me -f null -
you mean like rest should do, responses that give routings (or rather fragments) in headers? so that you can explore endpoints
Angius
Angius2mo ago
No, not quite What I want is, for example
// ClientBuilder/Program.cs
var app = new MyCoolApi();

using var file = Filep.Open("clients.ts");
using var stream = new StreamWriter(file);
foreach (var r in app.Routes)
{
stream.Write($$"""
export const {{r.Name}} = async (data) => {
await fetch('{{r.Url}}', {
method: '{{r.Method}}',
body: JSON.stringify(data)
});
};
""");
}
// ClientBuilder/Program.cs
var app = new MyCoolApi();

using var file = Filep.Open("clients.ts");
using var stream = new StreamWriter(file);
foreach (var r in app.Routes)
{
stream.Write($$"""
export const {{r.Name}} = async (data) => {
await fetch('{{r.Url}}', {
method: '{{r.Method}}',
body: JSON.stringify(data)
});
};
""");
}
ffmpeg -i me -f null -
mmh i remember asp net has an api to list registered controllers, although i never actually used it maybe it's IActionDescriptorCollectionProvider? maybe you can just recover all the controllers by d.i. and exploring them with reflection? im curious now, i will try it tomorrow