2

This is my first time trying to use the WEB API in a project and am not having any success with it...

I keep getting 404 errors when I try and reach my api route in Fiddler.

I tried looking a lot on the web and even here at the following link, but there are so many combinations, that I'm not sure what would work.

HTTP 404 Page Not Found in Web Api hosted in IIS 7.5

If somebody can please help me with this to get the right settings I would really appreciate it.

Here is my code: Web.config file:

<?xml version="1.0" encoding="utf-8"?>
<!--
  For more information on how to configure your ASP.NET application, please visit
  http://go.microsoft.com/fwlink/?LinkId=301879
  -->
<configuration>
  <configSections>
    <!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
    <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
    <sectionGroup name="applicationSettings" type="System.Configuration.ApplicationSettingsGroup, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
      <section name="FuelTicketImageRetrievalSvc.Properties.Settings" type="System.Configuration.ClientSettingsSection, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
    </sectionGroup>
  </configSections>
  <appSettings>
    <add key="webpages:Version" value="3.0.0.0" />
    <add key="webpages:Enabled" value="false" />
    <add key="ClientValidationEnabled" value="true" />
    <add key="UnobtrusiveJavaScriptEnabled" value="true" />
    <add key="AssignedGroup" value="FMS Maintenance Level 3" />
  </appSettings>
  <system.web>
    <compilation debug="true" targetFramework="4.5.1" />
    <httpRuntime targetFramework="4.5.1" />
  </system.web>
  <system.webServer>
    <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>
  <runtime>
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
      <dependentAssembly>
        <assemblyIdentity name="System.Web.Optimization" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="1.0.0.0-1.1.0.0" newVersion="1.1.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="WebGrease" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="0.0.0.0-1.5.2.14234" newVersion="1.5.2.14234" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Web.Helpers" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Web.WebPages" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="0.0.0.0-5.1.0.0" newVersion="5.1.0.0" />
      </dependentAssembly>
    </assemblyBinding>
  </runtime>
  <entityFramework>
    <defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework" />
    <providers>
      <provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
    </providers>
  </entityFramework>
  <system.serviceModel>
    <bindings />
    <client />
  </system.serviceModel>
  <applicationSettings>
    <FuelTicketImageRetrievalSvc.Properties.Settings>
      <setting name="FuelTicketImageRetrievalSvc_IncidentService_HPD_IncidentInterface_Create_WSService" serializeAs="String">
        <value>http://miavsbremweb/arsys/services/ARService?server=miavsbremapp.ryder.com&amp;webService=HPD_IncidentInterface_Create_WS</value>
      </setting>
    </FuelTicketImageRetrievalSvc.Properties.Settings>
  </applicationSettings>
</configuration>

WebApiConfig.cs file:

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

namespace FuelTicketImageRetrievalSvc
{
    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}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );
        }
    }
}

Global.asax.cs file:

using FuelTicketImageRetrieval;
using System.Web.Http;
using System.Web.Mvc;
using System.Web.Optimization;
using System.Web.Routing;

namespace FuelTicketImageRetrievalSvc
{
    public class WebApiApplication : System.Web.HttpApplication
    {
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            GlobalConfiguration.Configure(WebApiConfig.Register);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);
        }
    }
}

Controller method that I'm trying to call. It's just a dummy method that simply returns null with no parameters. It's name is FuelTicketImageRetrievalController:

public string GetSpecificFuelTicket()
        {
            try
            {
                return null;
            }
            catch (Exception ex)
            {
                return null;
            }
        }

The name of my project is called FuelTicketImageRetrievalSvc. I have verified through the web settings in the project that IIS Express is being used and is set to

http://localhost:11581/

url path call.

http://localhost:11581/FuelTicketImageRetrievalSvc/api/GetSpecificFuelTicket
Community
  • 1
  • 1
sagesky36
  • 4,542
  • 19
  • 82
  • 130

4 Answers4

0

You don't need FuelTicketImageRetrievalSvc in uri, it should work simply with /api/... that's what your route matches, having svc name there causes it to not match.

Konstantin
  • 3,254
  • 15
  • 20
  • Ok.. I'm getting a 500 error now... Trying to debug actually with a break point at that method. How do I handle the message that IE gives when it says "Do you want to open or save GetSpecificFuelTicket from localhost>" – sagesky36 May 01 '14 at 21:02
0

You need to add your controller in the path and remove your project

http://localhost:11581/api/FuelTicketImageRetrieval/GetSpecificFuelTicket

You remove the Controller part when referencing it - the /FuelTicketImageRetrieval/ is from the FuelTicketImageRetrievalController not the project. Web API will auto add the controller back on the name when looking for the correct class.

CharlesNRice
  • 3,219
  • 1
  • 16
  • 25
  • Ok.. I'm getting a 500 error now... Trying to debug actually with a break point at that method. How do I handle the message that IE gives when it says "Do you want to open or save GetSpecificFuelTicket from localhost>" – sagesky36 May 01 '14 at 21:01
  • Hit it with fiddler, then see click the raw tab to see exactly what is being sent back. Usually IE is complaining that it's getting data back it doesn't understand. JSON usually. But at least now your hitting your site :) Try returning back an empty string instead of null - maybe it can't sterilize null. Hard to say error 500 is a general error of something is wrong. – CharlesNRice May 01 '14 at 21:04
  • I am hitting it now. thanks.. I have another method called GetSpecificFuelTicket(int value). I'm calling it like so "http://localhost:11581/api/GetSpecificFuelTicketAsync/6460194", but am getting a 404 on this. Isn't this the correct way to call a method with a parameter? – sagesky36 May 01 '14 at 21:19
  • You should pass it as part of the query string GetSpecificFuelTicketAsync?value=6460194 you might need to add FromUrl Attribute to the method see http://www.asp.net/web-api/overview/formats-and-model-binding/parameter-binding-in-aspnet-web-api – CharlesNRice May 01 '14 at 23:24
0

For a quick guaranteed run (and sometimes preferred approach), add HTTP action prefix and route attributes before your method:

    [HttpGet]
    [Route("api/Products/SpecificFuelTicket")]
    public string GetSpecificFuelTicket()
    {
        try
        {
            return null;
        }
        catch (Exception ex)
        {
            return null;
        }
    }

Now, you can access it using URL:

http://localhost:xxxx/api/products/SpecificFuelTicket

Points to note:

  1. HTTPGet ensures that only Get action is mapped to this method
  2. Route value ensures a direct mapping to a URL. As REST standard, "Get", "Delete" etc.. are not used as prefix in URL. The HTTP action is used for that.
  3. Some methods are automatically mapped to suitable URLs, but since your class name is "FuelTicketImageRetrievalController" and method name is "GetSpecificFuelTicket", it is not trivial.
  4. Returning null is not an issue. it is returned serialized as "null".

For your another question to Charles, if you want to use URL "localhost:xxxx/api/GetSpecificFuelTicketAsync/6460194", and your method signature takes int, you can change the route prefix as following (again, not using "Get" in the route):

    [HttpGet]
    [Route("api/Products/SpecificFuelTicket/{value}")]
    public string GetSpecificFuelTicket(int value)
    {
        try
        {
            return "Your ticket is " + value.ToString();
        }
        catch (Exception ex)
        {
            return null;
        }
    }

However, as Charles suggested, using "api/Products/SpecificFuelTicket?value=6460194" format is perhaps better. Any parameter name in the method is automatically mapped to similar name query parameter. So, your method'd look like:

[HttpGet]
[Route("api/Products/SpecificFuelTicket")]
public string GetSpecificFuelTicket(int value)
{
   ....
}

For, a detailed understanding of URL mapping and routing web-API, refer to link:

  1. Attribute Routing in Web API 2
  2. Routing and Action Selection
Traze
  • 180
  • 8
0

I originally had a 404 error when I added WebApi support to my Mvc solution.

My global.asax.cs contained the lines:

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

What I found is that when I changed he WebApiConfig line, so that the code block became:

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

it fixed my problem

ossentoo
  • 1,675
  • 2
  • 20
  • 44