user1515364
user1515364

Reputation: 75

C# MVC and API in one project

I'm going to create a C# Web Application using MVC. I also want to have an API which mirrors the Web UI. As an example: if I have a web ui to "Create employee" I want a matching API call which does the same. It would take in the same information and follow the same process. I want to avoid duplication of code, so I'm looking for guidance on how to best structure my VS Project, so that I start the project correctly. Where should I put my models, my controllers etc? All suggestions appreciated.

Upvotes: 1

Views: 96

Answers (1)

Arno van Lieshout
Arno van Lieshout

Reputation: 1660

I would use ViewModels for the Views and the Api. This viewmodel is used to return to the browser as JSON or to build the View.

I would then use a library for the code handling and redirect to the libray in the Action methods in the view controller.

The View controller will recieve the ViewModel from the API or normal Action methods. It could pass this viewmodel along to the library or possibly translate it to a datamodel and then pass it to the library. In the same action method the view controller will get a model back from the library and rebuilds the viewmodel.

If you use a ViewModel the Api can easily translate it to and from JSON.

Upvotes: 1

Related Questions