41

I am working on a project in MVC that has mobile application so one thing is clear that we have to use Web API so it can used in mobile application.

After creating API when we started to develop Web site we are confused and had discussion on whether to use API or directly access to the Business object. And we ended up after having opinion form more experienced developer to consume Web API instead of using Business object directly.

I'm having confusion regarding to this solution structure.

1) Why we should use Web API and make HTTP request (which is time consuming) to get or put data instead of business object directly which is in same solution.

2) After having arguments they said what if client wants to host API and web on different cloud server and apply scaling only on API or may be he want to have different url for accessing API and Web (which is some what logical). So in that case should we call Web API from MVC application in same solution?

3) If we're hosting API and Web on different hosting so it means our Web will use WebClient and have HTTP call on each navigation. Is it right?

4) If we'll business object form both API and Web hosting on different server then if something change in BL will need to update build on both server.

5) Or we should create only one project for API and can add views or html pages to develop Web interface so in that way we can directly call API from ajax.

As per my knowledge #5 is the best solution or API is only for 3rd party access. If we have DB, EF, data layer and business layer in same solution then we should not use API to make HTTP calls and directly access business object. (correct me if I'm wrong)API is needed when mobile application or desktop or any one want to access application so we can have same repository and data layer.

In my scenario I've to create API as we also have mobile application, and in project API side we called business layer (separate project) and business layer communicate to data access layer (separate project). So my question is if we host our API and web to different servers then calling API which is a HTTP request may take longer rather than using method from business layer as we create the project and we've .dll of business layer. In API controller we just convert out put of our business to json format.

I've searched on internet but didn't get convincing answer. I've found a blog http://odetocode.com/blogs/scott/archive/2013/07/01/on-the-coexistence-of-asp-net-mvc-and-webapi.aspx discussing same point but again in that blog my question is why we need to consider scenario #3?

Update: We can have different API project and MVC project and we can call API from web using jvascript or can use MVVM pattern.

6
  • MVVM or MVC with view models? Jun 30, 2014 at 16:50
  • We're using MVC Jun 30, 2014 at 16:55
  • Ok then, then there's no correct answer really. There are benefits to only calling your API when it comes to improving their quality. (eating your own dogfood) There are also performance benefits to making inproc calls instead of calling through services. Jun 30, 2014 at 17:00
  • Google went through this question once. Their products are both services and websites. I believe they decided upon having their websites consume their own services. Jun 30, 2014 at 17:03
  • 2
    Yes. programmers.stackexchange.com/questions/148556/… and stackoverflow.com/questions/3590561/… are good resources. Some do, some don't. No real 'correct' way. Jun 30, 2014 at 17:41

3 Answers 3

46

Great question! I'm always looking for a better way to structure my projects.. Each point you raise has merit and having explored a variety of solution structures I have to say that I agree the majority of the comments here: there is no perfect solution. A few things to ask yourself when faced with this kind of problem: How complex is this application? With how many systems will I need to integrate -- or how many systems will need to integrate with this system? How much testing do I plan on doing? Is there a separate design/UI team? Will we need to scale? What constitutes a session?

Let's look at a couple of scenarios and ways to use a little clever engineering to make things really bang (and some tricks to make things a bit easier)..

Hosting Both API and Website in the Same Project
In this case, you may have a single solution with zero or more business layer projects and a single hybrid MVC/WebAPI project (as well as other projects - utility, etc).

Pro's
Everything is in one place.. No need to shoe-horn in complicated messaging (HttpClient calls), you can have shared session state (client and server via cookies, InProc/OutOfProc session, etc), connection pooling, shared logic, etc. Deployment could not be more simple.

Con's
Everything is in one place.. This is probably the most monolithic structure possible. There are no clearly defined interfaces between your layers.. You end up with high-cohesion. Lazy developers will avoid interfaces when dealing with this type of architecture which makes testing a huge pain. Scaling/co-locating the application will be difficult.

Uses
I would use this project structure for a one-off, internal, or simple application. Building a quick system for tracking basketball camp sign-up at the local Y? This is your architecture!

WebAPI and Website in Different Projects
I tend to prefer this case.. You have a single solution with one (or more) MVC project(s) and one WebAPI project.

Pro's
Modularization! Loose Coupling! Each project can stand alone, be tested separately, and can be managed differently. This allows you to more easily implement different caching strategies depending on your needs. By keeping solid boundaries between your different systems, you can more easily establish contracts which allow you to enforce specific usage patterns and cut-down on possible friction (read: fewer bugs with less opportunity to abuse the API). Scaling is a bit easier as you only need to scale the bits that are seeing high load. Integration becomes a bit easier to handle as well because you will need to have an idea about what your API is going to look like from the start.

Con's
Maintenance is a bit more difficult. Multiple projects means you will need project/feature owners to keep track of merges, contracts (interfaces), deployments, etc. Code upkeep, technical debt, error tracking, state management -- all become concerns as they might need to be implemented differently based upon your needs. These kinds of applications also require the most planning and curating as they grow.

Uses
Building an application that could have 100 users today and 100,000 next week/month? Does the application have to send notifications, manage complex workflows, and have multiple interfaces (web + mobile app + SharePoint)? Have lots of time on your hands and love solving 5000+ piece puzzles over the weekend? This is the architecture for you!

Tips
Having outlined the above, I can understand how your next project might look a bit daunting. No worries, here are a few tricks I've learned over the years..

  1. Try to use stateless sessions. On smaller systems, this might mean storing an encrypted cookie containing at least the current user's internal id and a timeout. Larger systems might mean storing an encrypted cookie with a simple session id which might be fetched from a datastore (redis, table storage, DHT, etc).. If you can store enough information so that you don't have to hit the main database on every request then you will be in a good place - but try to keep cookies under 1k.
  2. Be aware that there will probably be more than one model. Try to think in terms of models and projections (the links I found here were.. not good.. think: one man's inventory item is another man's order line item - same basic underlying structure, but different views). Some projects have a different model for each logical/conceptual boundary (i.e. using a specific model for communcation with a specific API.
  3. API's Everywhere! Anytime an object/class/structure exposes any data or behavior, you are establishing an API. Be mindful of how other entities or dependencies will be using this API. Think about how you might test this API. Consider what might be talking to this API (other objects via code? Other systems via a protocol?) and how that data is exposed (strongly typed? JSON? * cough * XML?).
  4. Build for what you have, not what you imagine that you will have two years from now. Another answer references YAGNI - they're absolutely correct! Solving imaginary problems makes your deadline imaginary. Set solid goals for your iterations and meet them. Deploy! A project in development is a project with only one user - you!
  5. YMMV (Your Mileage May Vary). There is only one absolute here: there is a problem, you are building a solution. Everything else is completely up in the air. Both solutions above can be made a wild success -- and a sucking failure. It is all up to you, your tools, and how you use them. Tread lightly, fellow developer!
3
  • 2
    Great answer! I wish I could award you something for your writing, but since I can't think of anything I'll just follow your Twitter. :P
    – Dan
    Jan 3, 2017 at 14:13
  • "strongly typed? JSON? * cough * XML" what am I missing? May 24, 2017 at 12:35
  • 1
    @AlexanderDerck I'm mentioning three different formatting options (although there are more).. the "joke" is that XML can be difficult to work with and can often add a good bit of overhead (serialization/deserialization). That isn't to say that sometimes there isn't a need (especially when working with external groups)..
    – Bobby D
    May 31, 2017 at 13:30
6

Directly accessing your business objects directly (I assume you mean in your controller) will be quicker & easier.

what if client wants to host API and web on different cloud server and apply scaling only on API or may be he want to have different url for accessing API and Web (which is somewhat logical)

Then you'll need to host them separately... but that doesn't sound very logical to me, surely you would want to scale both. Are you sure you need to cater for this requirement? That sounds like overkill. Remember YAGNI - if you don't need it, don't build it. When you need it, build it.

If it was me I'd build the site using the technology that fits the best the site, then when (if) you need a service that other people can call build that separately.

1
  • I totally agree with you becasue at the end of days scaling is important and separation of concern does matter for me. It's always good to think building n-tier architecture as technology changes that can be upgraded or maintained easily. For example, wrapping with docker container is another thing to consider in future. Dec 11, 2018 at 0:44
4

I would say; prefer MVC calling WebAPI through HTTPClient. It is overwhelming go around "core dll" logic but main advantage is that your overall system will have a single point access to domain objects on HTTP...Anyways down the line..with Micro Service Architecture picking-up AND apps already switching to Client Side Frameworks (AngularJS etc.)....better to treat MVC as another client...and disciple your team to manage APIs well...

KEEP IT SIMPE. Hope this help. Thanks..

3
  • Not sure why this was down voted but it is the best answer for good architecture imo
    – weagle08
    Mar 13, 2017 at 23:59
  • I was pondering on my situation where I thought it was a good idea to call API from own MVC app- but I think it's different from this and maybe many other questions which refer to this call from server logic. In my case I'll be actually calling it from my views where I'll have Vue forming complex UIs and passing the data to that API. Then I realized that it's legit because in my case it's actually calling from a view vs server-side items and any http calls would have been done anyway when considering any kind of UI- maybe even more so if ASP-made views . But, only works in JS environments. Feb 11, 2019 at 9:38
  • View calling API directly is a good thought....but MVC Views are generated from Server so you can also process data from server especially that is more relevant for server processing) before rendering partial views (Views)...RESS framework (RESS: Responsive Web Design + Server-Side Components)....BUT BEST USE PURE Client Frameworks (Angular/ReactJS) if you can avoid MVC totally... Mar 2, 2019 at 13:58

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.