Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert MVC empty project to Web API?

I created a an "Empty" for MVC 4. After coding some things out, I realized that an "Web API" project is better. I do not want to start over so is there a way to convert it to a Web API project instead? Below is a screenshot of what I am referring to. Any help would be greatly appreciated.

enter image description here

like image 252
TruMan1 Avatar asked May 11 '12 20:05

TruMan1


People also ask

Can we create Web API without MVC?

Web API and ASP.NET MVC Web API is a feature of ASP.NET MVC 4. This included with MVC 4 because of their similarities. That doesn't mean you always have to create ASP.NET MVC application for developing Web API. You can use Web API in any number of applications.

Can I use MVC controller as Web API?

In order to add a Web API Controller you will need to Right Click the Controllers folder in the Solution Explorer and click on Add and then Controller. Now from the Add Scaffold window, choose the Web API 2 Controller – Empty option as shown below. Then give it a suitable name and click OK.

How pass data from MVC controller to Web API?

vmGroup objvmGroup = new vmGroup(); string apiUrl = ConfigurationManager. AppSettings["baseurl"] + "/Application. API/SaveObject"; var client = new HttpClient(); client. BaseAddress = new Uri(apiUrl); client.

Is MVC and Web API same?

Only JSON and XML are present in Web API unlike MVC where return views, action results, etc are present.


1 Answers

You can add a Web API controller to an MVC project. In Solution explorer, right-click the Controllers folder, select Add Controller, then pick Web API controller.

The only other thing you need is the routing - I believe the "empty" MVC 4 project already includes a Web API route by default, so you should be OK. Look for something like:

  routes.MapHttpRoute(
      name: "DefaultApi",
      routeTemplate: "api/{controller}/{id}",
      defaults: new { id = RouteParameter.Optional }
  );

But if you want to convert an existing MVC controller to a Web API controller, there is no automatic way to do that.

like image 107
Mike Wasson Avatar answered Oct 05 '22 20:10

Mike Wasson