5

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

3 Answers 3

6

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.

Sign up to request clarification or add additional context in comments.

1 Comment

I have an existing MVC 4 project that I want to add an ApiController to. However, when I right-click the Controllers folder and select Add Controller, the scaffolding template dropbox only has 3 standard MVC options in it, not the six (3 for MVC and 3 for WebAPI) that you find in new projects created from scratch as WebAPI projects. I am guessing there are some new references I need to add, maybe some config changes, to do this?? Much less how to get the template choices to show up. I am hoping there might be an easy way to add/convert this? Thx!
2

If you truly want to migrate to a Web API project, the easiest thing to do is to just create a new blank Web API project. Then, copy in all the files from your old project, delete the old project and rename the new one.

The other option which may take more effort, is to create a new blank Web API project. Then, open the project file in a text editor and compare to your old project file, and make the necessary changes to the raw file. It's all in XML so it shouldn't be that hard.

Comments

1

Web API is better only if you want to expose data. If you need to render views (Razor or Web Forms), use ASP.NET MVC.

There is no automatic conversions as they do different things.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.