Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create Web API using MVC 3.0

I am using Visual Studio 2010 with .Net Framework 4 and ASP.NET MVC 3.

I want to make my controller method available to external applications like (Web sites, mobile apps, etc.) as a Web API. I tried finding the solution on web, however got all links pointing to "Web API2 Controllers" with VS 2013 e.g. this one. It is not possible for me to upgrade Visual Studio and .net framework at this stage.

Is there any way I can achieve this using .NET 4 and ASP.NET MVC 3?

like image 517
Anil Soman Avatar asked Feb 03 '14 04:02

Anil Soman


2 Answers

To get Web API in MVC3 project, please do following changes -

Step 1 - Create MVC3 Project with .Net 4.

Step 2 - Install Web API using Package Manager - Install-Package Microsoft.AspNet.WebApi -Version 4.0.30506

Step 3 - Add following route in Global.asax with referencing using System.Web.Http; -

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

Step 4 - Create a controller -

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Http;
using System.Web.Mvc;

namespace MvcApplication2.Controllers
{
    public class ValuesController : ApiController
    {

        public string Get()
        {
            return "1";
        }

    }
}

Step 5 - Execute the project and go to the url - /api/values. Thats it, we got our Web API running.

like image 84
ramiramilu Avatar answered Oct 27 '22 00:10

ramiramilu


There is no WebAPI for MVC 3. Upgrade to MVC 4 or use ServiceStack to implement RESTful layer

https://servicestack.net/

https://github.com/ServiceStack/ServiceStack/

like image 39
Andrei Avatar answered Oct 26 '22 23:10

Andrei