Dennis Puzak
Dennis Puzak

Reputation: 3736

ASP Web API method access from regular MVC controllers

I have a rather complex solution which I implemented using ASP Web API, among others. I have 3 projects in my solution worth mentinoing right now. One is a WebAPI containing only api methods. Other two are are the backend and frontend for my application. The backend uses a SPA approach loading mostly empty shells for views and filling everything with ajax acessing the API. The frontend on the other hand because of SEO concerns was decided to be implemented by more traditional means, aka most stuff is rendered server side. My question is, is it possible and good practice to simply call the web api methods from the frontend controlllers and send the results to the view? I don't see a point in duplicating most code in the regular controllers since it's all done with the api.

Any samples on this? I've been searching but couldn't find much.

Upvotes: 1

Views: 927

Answers (2)

Dmitry S.
Dmitry S.

Reputation: 8513

If you need to call Web API service from C# code (MVC controllers or elsewhere), HttpClient or WebClient can be used to call the services over HTTP.

If you need to simply reuse code, it should be abstracted into a class library (DLL) and referenced from the Web API and MVC projects.

Upvotes: 2

DShook
DShook

Reputation: 15664

I've run into this same situation and have used the Web API controllers from MVC controllers for a little while at least. You can do this simply by creating new objects of the Web API controllers then calling the appropriate methods off of them. I found this method works fine initially but creates the dependency that means your Web API can't change without also changing the MVC controllers as well.

My advice is to put as much functionality on your models that makes sense with partial classes, and if that is still inadequate then create another logic tier that contains all the shared business logic. You should not have duplicated logic in your MVC and Web API controllers, they should just serve as the glue to get the data served.

Upvotes: 1

Related Questions