2
votes

I am trying to call a web api service from a mvc client. After several errors that I've managed to solve, I am stuck on: "Failed to load resource: the server responded with a status of 404 (Not Found)".

My routing:

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

The web api:

public class TestServicesController : ApiController
    {
        [HttpGet]
        public HttpResponseMessage GetTest()
        {

            Console.Write("SUCCESS!!!!!");
            return Request.CreateResponse(HttpStatusCode.OK);
        }
    }

the client:

function test1() {
        $.ajax({
            url: "http://localhost:52285/api/Services/GetTest",
            type: 'GET',
            success: function () { alert("success!!"); },
        });
    }

I have tried searching for that problem, nothing worked.. please help!

2
Is your WebAPI and MVC client on the same server (i.e. localhost:52285)? I just want to eliminate any possibility of cross domain requests (which I know wouldn't cause the 404, but still, it would be good to know if they're on the same server or separate servers).Mike Marks
They are not on the same server. I had cross domain problems, but I solved that by adding <customHeaders> <add name="Access-Control-Allow-Origin" value="localhost:52274"> </customHeaders>dor.elmaliach
Have you tried using Fiddler to debug this? I discovered Fiddler some time ago, and it's so useful when trying to figure out why GET/PUT/POST/etc. requests aren't successful. fiddler2.comMike Marks
I am not sure what I am looking for there.. Is there a way to figure out was is the path to the service, from the project?dor.elmaliach
The path to the service, your WebAPI in other words, should be simple to find out. It's simply your WebAPI project > controller > action. Look in your WebAPI project, at your controller. Does this make sense? Basically: server/WebAPI project/controller/action/optional parametersMike Marks

2 Answers

1
votes
    [WebMethod]
    [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
    public static HttpResponseMessage GetTest()
    {

        Console.Write("SUCCESS!!!!!");
        return Request.CreateResponse(HttpStatusCode.OK);
    }

One thing I noticed is that the GetTest method is not static and without WebMethod attribute.

0
votes

I faced same issue and following change in Global.asax.cs worked for me.

    protected void Application_Start()
    {
        AreaRegistration.RegisterAllAreas();
        GlobalConfiguration.Configure(WebApiConfig.Register); //You need to add this line
        RouteConfig.RegisterRoutes(RouteTable.Routes);
    }