Monday, September 1, 2014

Setup an MVC 5 Razor Site with WebAPI in 3 Minutes

The purpose of this tutorial is to provide a quick walkthrough on how to setup a single project which will house both an MVC 5 site and a JSON WebAPI.  For more information on this scaffolding, look for tutorials on One ASP.NET.

Using Visual Studio 2013:

Select: New Project --> Visual C# --> Web --> ASP.NET MVC 5 Web Application

Give your Project a Friendly Name.
Browse to a good location for your Local Workspace.
Click Create.

Your MVC 5 application will scaffold and load into Visual Studio.
Click RUN.

Your project should compile and you should see a Sample Website in your browser.
Click STOP.

Right Click on your Project in Solution Explorer.
Select: Add --> Folder.
Name the folder Controllers.API (this important step will create a namespace container for your API controllers).
Right-click the Controllers.API folder.
Select: Add --> New Scaffolded Item.
Select: Common --> MVC --> WebAPI --> Web API 2 Controller......
    (NOTE:  If you do not have the WebAPI option, you will need to install a NuGet package for Microsoft ASP.NET Web API 2.2)
Click ADD.

Open App_Start/WebApiConfig.cs.
Paste the following into the Register() method:

            //Use JSON instead of XML
            var json = config.Formatters.JsonFormatter;
            json.SerializerSettings.PreserveReferencesHandling = Newtonsoft.Json.PreserveReferencesHandling.Objects;
            config.Formatters.Remove(config.Formatters.XmlFormatter);
            json.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;

***Please refer to other tutorials on how to build out an MVC 5 app, WebAPI, Entity Framework, or Repository Layer.










No comments: