ASP.NET Core 101 - Enhancing your Web API: Part 1 [8 of 13]

we are talking about the need for a single responsibility principle or what do they call that, separation of concerns?

Earlier, you may made me make a "Models" folder, and that's where we're currently keeping things,and "Pages" are views.
So I guess all that's missing is the controller.Here I could make an empty API controller,I think that probably worked for our needs. 

So why even(还;) have then MVC? What's the point?

the idea is that in separation of concerns,you want to have the model that knows how to talk to the database.You want to have the controller, that is your orchestrator(协调者),that has left hand in the
database and right hand in the views, and then your views.Views know nothing about anything.They only know about how to display information, display data.
Again, that's great because it's like the whole ignorance is bliss(满意) for code. If you want to reuse the stuff or expand on it later,it's a lot easier to do that if you don't have so many dependencies between.

If your object knows nothing about anything other than it's one job,it's a much more useful object. If your object knows all about the Internet,and then the Internet goes away, who knows what happens?
I don't know. But the problem is if it knows everything,you end up with these giant monolith(巨型) classes that you've probably seen before,you've probably made one before if you're not new to programming itself, and then regret it later when you try to find or do anything else with that later.

ProductsController

复制代码
namespace ContosoCrafts.WebSite.Controllers
{
    [ApiController]
    [Route("[controller]")]
    public class ProductsController : ControllerBase
    {
        public ProductsController(JsonFileProductService productService)
        {
          
        }
    }
}
复制代码

JSON File product service,that's where our products come from. We're going to need one of those.So we could new one,we can make one in the old days but now we're using the services technique that is available to us in ASP.NET.So we don't actually knew them, we don't go var j equals new.Instead, we just ask for them and we ask for them by adding them to our constructor.

Then we need to hold it somewhere,have it lying around somewhere so we'll go and say, "JsonFileProductService".Then we need to be able to get that, whenever.

复制代码
namespace ContosoCrafts.WebSite.Controllers
{
    [ApiController]
    [Route("[controller]")]
    public class ProductsController : ControllerBase
    {
        public ProductsController(JsonFileProductService productService)
        {
            ProductService = productService;
        }

        public JsonFileProductService ProductService { get; }
    }
}
复制代码

So when who makes controllers right? I mean, we don't.ASP.NET just makes them.There's a controller factory in fact.

we said, "On get."There's a similar model,if you're going to do things with controllers, isn't there? Yeah. I believe it has to do with HTTP. So you'd have HTTP POST or GET.Let's use GET in this case.

复制代码
namespace ContosoCrafts.WebSite.Controllers
{
    [ApiController]
    [Route("[controller]")]
    public class ProductsController : ControllerBase
    {
        public ProductsController(JsonFileProductService productService)
        {
            ProductService = productService;
        }

        public JsonFileProductService ProductService { get; }

        [HttpGet]
        public IEnumerable<Product> Get()
        {
            return ProductService.GetProducts();
        }
    }
}
复制代码

startup

Did we tell ASP.NET that controllers are a thing even?
Well, we mentioned before that our application uses routing and uses endpoints. We added that JSON File product-service, but yeah we didn't tell them about Controllers.

So why don't we add a controller service under the configure services method.

// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
    services.AddTransient<JsonFileProductService>();
    services.AddControllers();
}

Exactly. So this is a very common pattern here.Add stuff, and then you use stuff.So back under the endpoints land,we're going to add another endpoint, we're going to map to our controller.

复制代码
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }
    else
    {
        app.UseExceptionHandler("/Error");
        // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
        app.UseHsts();
    }

    app.UseHttpsRedirection();
    app.UseStaticFiles();
    app.UseRouting();
    app.UseAuthorization();

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

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

Interesting, remember how we talked about this? Razor pages/privacy/error.Controllers, you can't see it but it will be slash(斜杆) products because we routed it as slash products because that's the name of our controller.

posted @   FH1004322  阅读(132)  评论(0)    收藏  举报
点击右上角即可分享
微信分享提示