locked
Integration of Web API in MVC application RRS feed

  • Question

  • User2097725413 posted

    Hi

    I am working on MVC, dot net 4.0 framework application, I want to integrate Web API in existing MVC application.

    While accessing Web API I am getting exception as "404 Not Found".

    I used following configuration in application,

    Global.asax

    protected void Application_Start()
    {
    AreaRegistration.RegisterAllAreas();

    RegisterGlobalFilters(GlobalFilters.Filters);

    RegisterRoutes(RouteTable.Routes);

    }


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


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

    routes.MapRoute(
    "Default", // Route name
    "{controller}/{action}/{id}", // URL with parameters
    new { controller = "Home", action = "Index", id = UrlParameter.Optional }, // Parameter defaults
    new string[] { "ExtranetWeb.Controllers" }
    );

    routes.MapRoute("ErrorPage", "error", new { controller = "Home", action = "Error" });
    }

    Web.Config

    <system.web.webPages.razor>
    <host factoryType="System.Web.Mvc.MvcWebRazorHostFactory, System.Web.Mvc, Version=5.2.2.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
    <pages pageBaseType="System.Web.Mvc.WebViewPage">
    <namespaces>
    <add namespace="System.Web.Mvc" />
    <add namespace="System.Web.Mvc.Ajax" />
    <add namespace="System.Web.Mvc.Html" />
    <add namespace="System.Web.Optimization" />
    <add namespace="System.Web.Routing" />
    </namespaces>
    </pages>
    </system.web.webPages.razor>

    <system.webServer>
    <modules runAllManagedModulesForAllRequests="true" />
    <httpProtocol>
    <customHeaders>
    <add name="Cache-Control" value="no-cache, no-store" />
    <add name="Pragma" value="no-cache" />
    <add name="Expires" value="-1" />
    </customHeaders>
    </httpProtocol>
    <handlers>
    <remove name="ExtensionlessUrlHandler-Integrated-4.0" />
    <remove name="OPTIONSVerbHandler" />
    <remove name="TRACEVerbHandler" />
    <add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="*" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
    </handlers>
    </system.webServer>

    Web API Controller -

    [RoutePrefix("api/fsaservice")]
    public class FSAController : ApiController
    {
    [HttpGet]
    [Route("getproducts")]
    public IHttpActionResult GetProducts()
    {
    List<System.Web.Mvc.SelectListItem> lst = new List<System.Web.Mvc.SelectListItem>();
    lst.Add(new System.Web.Mvc.SelectListItem { Text = "Item1", Value = "Item1" });
    lst.Add(new System.Web.Mvc.SelectListItem { Text = "Item2", Value = "Item2" });
    lst.Add(new System.Web.Mvc.SelectListItem { Text = "Item3", Value = "Item3" });
    lst.Add(new System.Web.Mvc.SelectListItem { Text = "Item4", Value = "Item4" });

    return Ok(lst);
    }
    }


    Using above changes in code , till I am unable to connect Web API, getting "404 Not Found" exception.

    Kindly let us know how to resolve this type of issue.

    Tuesday, October 22, 2019 4:06 PM

All replies

  • User475983607 posted

    You did not tell us what URL returned the 404.   Try configuring Attribute routing.

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

    I build a test using your code and the code works as expected.

        [RoutePrefix("api/fsaservice")]
        public class FSAControllerController : ApiController
        {
            [HttpGet]
            [Route("getproducts")]
            public IHttpActionResult GetProducts()
            {
                List<System.Web.Mvc.SelectListItem> lst = new List<System.Web.Mvc.SelectListItem>();
                lst.Add(new System.Web.Mvc.SelectListItem { Text = "Item1", Value = "Item1" });
                lst.Add(new System.Web.Mvc.SelectListItem { Text = "Item2", Value = "Item2" });
                lst.Add(new System.Web.Mvc.SelectListItem { Text = "Item3", Value = "Item3" });
                lst.Add(new System.Web.Mvc.SelectListItem { Text = "Item4", Value = "Item4" });
    
                return Ok(lst);
            }
        }

    URL

    http://localhost:52441/api/fsaservice/getproducts

    Of course your URL will be different.  At least the port.

    Tuesday, October 22, 2019 4:16 PM
  • User2097725413 posted

    Hello,

    I added "config.MapHttpAttributeRoutes()" configuring attribute and re-arranged Global.asax order as follows

    AreaRegistration.RegisterAllAreas();

    //Register for Web APi
    GlobalConfiguration.Configure(WebApiConfig.Register);

    RegisterGlobalFilters(GlobalFilters.Filters);
    RegisterRoutes(RouteTable.Routes);

    RegisterContentBundles();

    But after adding all above changes till the Web API not working, gives status as "404 Not Found" in Postman and Postman body loads page not found related html code.

    Also its not returning any URL in 404 status.

    Please suggest how to fix this type of issues.

    Wednesday, October 23, 2019 9:40 AM
  • User-17257777 posted

    Hi Uday Mahajan,

    It seems you can't put "MapHttpRoute" in the RouteConfig.cs. To solve this problem, you can

    1. Create a new class "WebApiConfig" under the App_Start folder like this:

    public class WebApiConfig
        {
            public static void Register(HttpConfiguration configuration)
            {
                configuration.MapHttpAttributeRoutes();
    
                configuration.Routes.MapHttpRoute(
                    name: "DefaultApi",
                    routeTemplate: "api/{controller}/{id}",
                    defaults: new { id = RouteParameter.Optional }
                );
            }
        }

    2. Call GlobalConfiguration.Configure(WebApiConfig.Register) in Application_Start() (in file Global.asax.cs). it should before registering the default Web Application route.

    protected void Application_Start()
            {
                AreaRegistration.RegisterAllAreas();
                GlobalConfiguration.Configure(WebApiConfig.Register);
                FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
                RouteConfig.RegisterRoutes(RouteTable.Routes);
                BundleConfig.RegisterBundles(BundleTable.Bundles);
            }

    For more details, refer to

    https://stackoverflow.com/a/34194801/7609093

    Best Regards,

    Jiadong Meng

    Wednesday, October 23, 2019 9:49 AM
  • User753101303 posted

    Hi,

    Could you confirm which url you are testing? By any url you mean your site doesn't return anything not even MVC pages? Could it be that your site is installed under a child application root ie at https://site.com/myapp rather than at https://site.com ?

    When I really have a hard time I start by testing the simplest thing I can.

    Wednesday, October 23, 2019 11:26 AM