Reputation: 1
I'm building a web application using ASP.NET MVC6 that needs to be accessible via a web browser (via Views), as well as from mobile applications via Web API. The thing is that I would like to avoid duplicating business logic in controllers.
I know that MVC6 controllers return an IActionResult. When used as an MVC controller, the IActionResult might be a view. When used as a Web API controller, the IActionResult might be data (such as a list of products). The same controller might have actions (two different actions) that return both views and data.
But my requirement is to have one single method which can be used to render views when called in normal way in form of website and return data when called as Web API method.
Upvotes: 0
Views: 648
Reputation: 6011
As you’re already aware, MVC Controllers and Web API Controllers are now exactly the same. They’ve been unified as of MVC 6.0.
When you say you’d like to avoid duplicate business logic in the Controllers, may I ask why is it like that in the first place?
Do you have/shouldn’t you have some sort of Class Library project acting as your Business Layer in which you store all your relevant business rules?
For example:
In addition, you want the ability for your application to be viewed from within classic browser as much as from mobile devices. Have you considered building a SPA (Single Page Application)
which gets you best of both worlds?
The SPA
approach, will allow you to create Views and using a client side framework (ex: Angular) will allow you to invoke your WebAPI which in turn would invoke your Contoso.Service
layer.
Unless, of course, your mobile app is a native one that only needs to invoke your WebAPI
If there is a way for an IActionResult
to either return a View
or some Data
, the concern I have is that this IActionResult
may start growing and having some discoverable logic in them which may be hard to maintain/debug in the long run.
You also increase the likelihood of regression when you modify its behavior since you’ll need to test both the Views
and the mobile app
.
With little I know about your project, I’d take a look at SPA approach to see if it fits your need(s).
Upvotes: 0