Search code examples
c#asp.net-web-apiweb-applicationscontroller

Facing Issue in using Asp.net Web Api with details given below:


I Created the Web Api application with two Controllers and the first one is HomeController in which I created the action named ApiDataView and create the view of this action and calling the another action named GetNames in which I created in another Controller named APITESTController and I am calling this GetNames List<string> in ApiDataView View but On button click I cannot get the values of this GetNames action.

My Code:

Home Controller:

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

namespace My_Work.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            return View();
        }
        [HttpGet]
        public ActionResult ApiDataView()
        {
            return View();
        }
    }
}

APITest Controller:

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

namespace My_Work.Controllers
{
    public class APITestController : ApiController
    {
        public List<string> GetNames()
        {
            List<string> names = new List<string>() { "Zeeshan", "Uzair", "Nouman" };
            return names;
        }
    }
}

ApiDataView View:

@{
    Layout = null;
}
<!DOCTYPE html>
<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>APIDataView</title>
    <script> src="~/Scripts/jquery-1.7.1.js" </script>
</head>
<body>
    <div>
        <input type="button" id="btn1" value="Show Name" />
        <ul id="nl">
            <li>ABC</li>
        </ul>
    </div>
</body>
</html>
<script>
    $("#btn1").click(function () {
        $("#nl").empty();
        $.getJSON("api/APITest/GetNames", function (data) {
            $.each(data, function (id,val) {
                $("#nl").append("<li>" + val + "</li>");
            });
        });
    });
</script>

WebApiConfig App_Start Folder:

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

namespace My_Work
{
    public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            // Web API configuration and services

            // Web API routes
            config.MapHttpAttributeRoutes();

            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{action}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );
            var xmlType =
                config.Formatters.XmlFormatter.SupportedMediaTypes.FirstOrDefault(t => t.MediaType == "application/xml");
                config.Formatters.XmlFormatter.SupportedMediaTypes.Remove(xmlType);
        }
    }
}

RouteConfig App_Start Folder:

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

namespace My_Work
{
    public class RouteConfig
    {
        public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

            routes.MapRoute(
                name: "Default",
                url: "{controller}/{action}/{id}",
                defaults: new { controller = "Home", action = "ApiDataView", id = UrlParameter.Optional }
            );
        }
    }
}

This is the code where I am getting GetNames action values:

<script>
    $("#btn1").click(function () {
        $("#nl").empty();
        $.getJSON("api/APITest/GetNames", function (data) {
            $.each(data, function (id,val) {
                $("#nl").append("<li>" + val + "</li>");
            });
        });
    });
</script>

Output:

enter image description here

and now On button click I cannot get the values of GetNames action. Any help is appreciated.


Solution

  • The path you have given is relative means it will append your path "api/APITest/GetNames" after the current URL so the request path created is "/Home/api/APITest/GetNames" which do not exist that's why you're getting 404 error (check in browser's console). To fix this, give your path like this "/api/APITest/GetNames" to make it absolute means start from "/api".

    $.getJSON("/api/APITest/GetNames", function (data) {});