August 13, 2013
@ 10:12 AM
1. Config global to use WebApi in MVC4
 protected void Application_Start()
        {
            RouteTable.Routes.MapHubs();

            AreaRegistration.RegisterAllAreas();

            WebApiConfig.Register(GlobalConfiguration.Configuration);
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);

        }
2. Add your mapping in App_Start folder WebApiConfig.cs
public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );
            config.Routes.MapHttpRoute(
             name: "GetTaskApi",
             routeTemplate: "api/{controller}/{action}/{id}/{token}",
             defaults: null
         );
            /*
             config.Routes.MapHttpRoute(
            name: "ApiById",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional },
            constraints: new { id = @"^[0-9]+$" }
        );

        config.Routes.MapHttpRoute(
            name: "ApiByName",
            routeTemplate: "api/{controller}/{action}/{name}",
            defaults: null,
            constraints: new { name = @"^[a-z]+$" }
        );

        config.Routes.MapHttpRoute(
            name: "ApiByAction",
            routeTemplate: "api/{controller}/{action}",
            defaults: new { action = "Get" }
        );
             */
        }
    }
3 Add you WebApi Controller
public class TaskController : ApiController
    {   
        // http://localhost:45897/api/task/1
        public TaskDetailResponse Get(int id)
                {
                    return  apiService.GetTaskDetails(new TaskDetailRequest(){Id=id});
                }
        // http://localhost:45897/api/task/gettask/1/testtoken
        public TaskDetailResponse GetTask([FromUri]TaskDetailRequest request)
        {
                    
            var response = apiService.GetTaskDetails(request);
            return response;
        }

    }

4. in Firefox and Chrome, if you visit the link, it will return xml, but in IE, it will let you save a json file



5. User jQuery.getJSON to call the api
function getData() {
        var apiUrl = 'api/task';
        var id = 1;
        $.getJSON(apiUrl + '/' + id)
            .done(function (data) {
                alert('ok!');
            })
            .fail(function (jqXHR, textStatus, err) {
                alert(err);
            });
    }