Organizing Master-Detail Controllers ASP.Net Web API - asp.net

I am trying to determine the best way to implement the retrieval of detail records based upon the master's ID.
Obviously you would set up API controllers for both master and detail.
Solutions I've considered:
Have API consumers use OData to get all details filtered by a master ID. While I don't have an issue with this solution, I kinda feel bad putting that onto the API consumer and feel it is something that should be handled internally by the API
Go against the convention of just having the Get/Put/Post/Delete methods and create an action of "GetMastersDetails" on the detail controller and make it accessible via routing. While this would certainly work, I feel this gets away from the whole point of Web API (to an extent).
Create a 3rd controller named "MastersDetailsController" which would have a Get based upon a master ID with different possible return types:
Which would return a list of detail IDs which would then be used to call a Get on the details controller to get those actual details
Which would return a list of actual detail objects. What I don't like about that is having a controller returning a different type than what it is based upon.

Option 2 will be fine. Option 1 opens up a lot more risk depending on your scenario, and what you want to allow the user to get at.
It's not really "against convention" to add custom methods to an ApiController. You can do that however you like. It would only be "against convention" if you did so and used the wrong HTTP methods (i.e. a GET when you're deleting something in your custom method).

I'd go with either #1 or #2.
For #1, OData support enables not only the scenario you describe but offers a lot of additional functionality which might be desired in the future.
For #2, I don't think it gets away from the point of Web API's. Maybe a bit from a true RESTful service, but it's easy to implement and easy to understand.

Related

Symfony 3 - Should I create two different controllers for REST and normal HTML?

Symfony 3 - Should I create two different controllers for REST and normal HTML?
I already have a web application where I am using Symfony controller and twig html templates. So I already have the business logic written to fetch the content. Now I want to expose REST API to share this content with third party. Should I write a separate controller using fosrestbundle ? Or can I use the same controller for both json and HTML? If yes, how?
This might be a highly subjective question and each programmer will have another opinion to this.
I'll try to give you an answer ...
Is the REST Data requested by the page which gets already handled by the controller it might be a better choice to add just a simple json returning function for simplicity.
Are the requirements bigger and for example a third party application may have access to this, you should go with a dedicated REST API, since there may be complete different requirements for security, response times and so on.
At the one hand, a simple Controller can't give you that features and on the other hand it's much cleaner to follow the single responsibility principle with an extra API.
But consider also creating an extra API takes also more time.
So now you should decide yourself for now and for future whether you need an dedicated API or not. The need of third party access sounds to me to go for an extra API.

Who's responsibility should be to paginate controller/domail service/repository?

My question might seem strange for pros but please take to account that I am coming from ruby on rails world =)
So, I am learning ASP.NET Core. And I like what I am seeing in it compared to rails. But there is always that but... Let me describe the theoretical problem.
Let's say I have a Product model. And there are over 9000 records in the database. It is obvious that I have to paginate them. I've read this article, but it seems to me that something is wrong here since the controller shouldn't use context directly. It has to use some repository (but that example might be provided in such a way only for simplicity).
So my question is: who should be responsible for pagination? Should it be the controller which will receive some queryable object from the repository and take only those records it needs? Or should it be my own business service which does the same? Or should the repository has a method like public IEnumerable<Product> ListProducts(int offset, int page)?
One Domain-Driven-Design solution to this problem is to use a Specification. The Specification design pattern describes a query in an object. So you might create a PagedProduct specification which would take in any necessary parameters (pageSize, pageNumber, filter). Then one of your repository methods (usually a List() overload) would accept an ISpecification and would be able to produce the expected result given the specification. There are several benefits to this approach. The specification has a name (as opposed to just a bunch of LINQ) that you can reason about and discuss. It can be unit tested in isolation to ensure correctness. And it can easily be reused if you need the same behavior (say on an MVC View action and a Web API action).
I cover the Specification pattern in the Pluralsight Design Patterns Library.
For first, I would like to remind you that all such examples you linked are overly simplified, so it shouldn't drive you to believe that that is the correct way. Simple things, with fewer abstraction layers are easier to oversee and understand (at least in the case of simple examples for beginners when the reader may not know where to look for what) and that's why they are presented like that.
Regarding the question: I would say none of the above. If I had to decide between them then I would say the service and/or the repository, but that depends on how you define your storage layer, etc.
"None of the above", then what? My preference is to implement an intermediary layer between the service layer and the Web UI layer. The service layer exposes manipulation functionality but for read operations, exposes the whole collection as an IQueryable, and not as an IEnumerable, so that you can utilize LINQ-to-whatever-storage.
Why am I doing this, many may ask. Because almost all the time you will use specialized viewmodels. To display the list of products on an admin page, for example, you would need to display values of columns in the products table, but you are very likely to need to display its category as well. Very rarely is it the case that you need data only from one table and by exposing the items as an IQueryable<T> you get the benefit of being able to do Selects like this:
public IEnumerable<ProductAdminTableViewModel> GetProducts(int page, int pageSize)
{
backingQueryable.Select(prod => new ProductAdminTableViewModel
{
Id = prod.Id,
Category = prod.Category.Name, // your provider will likely resolve this to a Join
Name = prod.Name
}).Skip((page - 1) * pageSize).Take(pageSize).ToList();
}
As commented, by using the backing store as an IQueryable you will be able to do projections before your query hits the DB and thus you can avoid any nasty Select N+1s.
The reason that this sits in an intermediary layer is simply you do not want to add references to your web project neither in your repo nor in your service layer (project) but because of this you cannot implement the viewmodel-specific queries in your service layer simply because the viewmodels cannot be resolved there. This implies that the viewmodels reside in this same project as well, and to this end, the MVC project only contains views, controllers and the ASP.NET MVC-related guttings of your app. I usually call this intermediate layer as 'SolutionName.Web.Core' and it references the service layer to be able to access the IQueryable<T>-returning method.

Passing ViewModel from Presentation to Service - Is it Okay?

In one of my views, I have a ViewModel which I populate from two tables, and then bind a List<ViewModel> to an editable GridView (ASP.NET Web Forms).
Now I need to send that edited List<ViewModel> back to the Services layer to update it in the database.
My question is - is it Okay to send the ViewModel back to Services, or should it stay in the Presentation? If not - should I better use a DTO? Many thanks.
Nice question !
After several (hard) debates with my teammates + my experience with MVC applications, I would not recommend to pass viewmodel to your service / domain layer.
ViewModel belongs to presentation, no matter what.
Because viewModel can be a combination of different models (e.g : 1 viewModel built from 10 models), your service layer should only work with your domain entities.
Otherwise, your service layer will end up to be unusable because constrained by your viewModels which are specifics for one view.
Nice tools like https://github.com/AutoMapper/AutoMapper were made to make the mapping job.
I would not do it. My rule is: supply service methods with everything they need to do their job and nothing more.
Why?
Because it reduces coupling. More often than not service methods are addressed from several sources (consumers). It is much easier for a consumer to fulfil a simple method signature than having to build a relatively complex object like a view model that it otherwise may have nothing to do with. It may even need a reference to an assembly it wouldn't need otherwise.
It greatly reduces maintenance effort. I think an average developer spends more than 50% of his time inspecting and tracking existing code (maybe even much more). Now everybody knows that looking for something that is not there takes disproportionally much time: you must have been everywhere to be sure. If a method receives arguments (or object with properties) that are not used directly or further down the call stack you or others will walk this long road time and again.
So if there is anything in the view model that does not play a part in the service method, don't use it to call the method.
Yes. I am pretty sure it is ok.
Try to use MS Entity Framework and it will help you allots.

Endpoint design for a data retrieval orientated ASP.NET webapi

I am designing a system that uses asp.net webapi to serve data that is used by a number of jquery grid controls. The grids call back for the data after the page has loaded. I have a User table and a Project table. In between these is a Membership table that stores the many to many relationships.
User
userID
Username
Email
Project
projectID
name
code
Membership
membershipID
projectID
userID
My question is what is best way to describe this data and relationships as a webapi?
I have the following routes
GET: user // gets all users
GET: user/{id} // gets a single user
GET: project
GET: project/{id}
I think one way to do it would be to have:
GET: user/{id}/projects // gets all the projects for a given user
GET: project/{id}/users // gets all the users for a given project
I'm not sure what the configuration of the routes and the controllers should look like for this, or even if this is the correct way to do it.
Modern standard for that is a very simple approach called REST Just read carefully and implement it.
Like Ph0en1x said, REST is the new trend for web services. It looks like you're on the right track already with some of your proposed routes. I've been doing some REST design at my job and here are some things to think about:
Be consistent with your routes. You're already doing that, but watch out for when/if another developer starts writing routes. A user wants consistent routes for using your API.
Keep it simple. A major goal should be discoverability. What I mean is that if I'm a regular user of your system, and I know there are users and projects and maybe another entity called "goal" ... I want to guess at /goal and get a list of goals. That makes a user very happy. The less they have to reference the documentation, the better.
Avoid appending a ton of junk to the query string. We suffer from this currently at my job. Once the API gets some traction, users might want more fine grained control. Be careful not to turn the URL into something messy. Something like /user?sort=asc&limit=5&filter=...&projectid=...
Keep the URL nice and simple. Again I love this in a well design API. I can easily remember something like http://api.twitter.com. Something like http://www.mylongdomainnamethatishardtospell.com/api/v1/api/user_entity/user ... is much harder to remember and is frustrating.
Just because a REST API is on the web doesn't mean it's all that different than a normal method in client side only code. I've read arguments that any method should have no more than 3 parameters. This idea is similar to (3). If you find yourself wanting to expand, consider adding more methods/routes, not more parameters.
I know what I want in a REST API these days and that is intuition, discoverability, simplicity and to avoid having to constantly dig through complex documentation.

Is a custom AutoMapper ValueResolver an (in)appropriate place for fetching data?

Let's say that in my ASP.NET MVC project, I have a ViewModel that is used on a form for editing a product. Among many other fields, I have a list of product types I want the user to be able to select from, in a dropdown.
When I map my domain object to my ViewModel, I'm calling a service to fetch the domain object, then using AutoMapper to map it to the ViewModel. To fill a dropdown for that list of product types, I call another service, which fetches that data from the database and uses it to populate another property on my ViewModel.
What I'm wrestling with is whether it's better to call that secondary service explicitly in the controller, versus potentially putting that call into a custom ValueResolver class and configuring my mapping to use it.
I like the prospect of removing the dependency on the product type service from my controller (because there are a lot of these, and the controller ends up with a lot of dependencies), but I'm worried that putting this sort of logic (which can hit the database) into a ValueResolver is an inappropriate use of a ValueResolver and might violate what I'd call the principle of least surprise. (I.e., I probably wouldn't expect mapping code to be causing database requests.)
Is this a common thing to use a ValueResolver for?
Answered by Jimmy Bogard on the AutoMapper Mailing List:
Yeah, it's definitely not uncommon. Drop-down list data sources....man, they're the toughest thing to figure out in our ViewModel world.
Keep in mind that you'll need to worry about the POST scenarios, refilling-in the information for validation failures, etc.

Resources