ASP.NET Core 101 - Making a Simple API [7 of 13]

This data is coming out of a JSON file,but again it could come out of anywhere.In fact, this data could have come out of like a web service from someone else's web service that we would call. Or someone could call us,and we're a web service.

API

API, Application Programming Interface,and that's the ability to go and call another thing in a formalized(使成为正式的; 形式化) way.

So everyone got together on the internet one day and decided that JavaScript was the way,and JSON, the JavaScript Object Notation(符号,记号),is a good way to express things.

endpoint

If I hit "Slash(斜杆/) Privacy", I get a privacy policy page.(\Pages\Privacy.cshtml)

http://localhost:1234/Privacy

I don't have a Products, but do I need a Products page? Do I need a Products end point, a place to land when you say slash Products? This endpoint of where a URL turns into some work is an endpoint and ASP.NET.

let's look in startup.cs, the "configure" method,we see that there's an endpoint,and then we say Map Razor Pages.

endpoints.MapRazorPages();

It is because of that line(行) code that slash privacy and slash nothing actually works.

So it turns out you can say endpoints.and look, you can map all kinds of stuff; map this,MapControllers,MapBlazorHub.

 app.UseEndpoints(endpoints =>
{
       endpoints.MapRazorPages();
       endpoints.MapControllers();
       endpoints.MapBlazorHub();
});

Well, you can MapGet. So when someone does a Get, we can do some stuff.

So I noticed you were trying to use the forward slash products thing,so why don't we try to insert that as a route. So that'll become our new endpoint or endpoint route.
You should go and take a look in the Docs about the subtle(不易察觉的; 不明显的; 微妙的;) differences between routing and endpoints.Endpoints is a little bit more flexible(能适应新情况的; 灵活的; 可变动的;) for what we're doing.

endpoints.MapGet("/products", (context) => 
{
    var products = app.ApplicationServices.GetService<JsonFileProductService>().GetProducts();
    var json = JsonSerializer.Serialize<IEnumerable<Product>>(products);
    return context.Response.WriteAsync(json);
});

Alt+Enter

小灯泡提示(快速操作快捷键), 以前的vs可以通过Resharper插件实现。

JsonView

是一款浏览器非常实用的格式化和语法高亮JSON格式数据查插件。

posted @ 2019-11-28 00:33  FH1004322  阅读(100)  评论(0)    收藏  举报