3
votes

I have a WebAPI method here:

http://localhost:50463/api/movies

and when accessing it from a browser it loads perfectly.

In my project (the same project as where Web API resides) when calling the method from AngularJS I get an error 500:

Failed to load resource: the server responded with a status of 500 (Internal Server Error)

When I click the link in the error it loads the data perfectly.

The routing for WebAPI is as follows:

config.Routes.MapHttpRoute("DefaultApiGet", "Api/{controller}", 
    new {action = "Get"}, 
    new {httpMethod = new HttpMethodConstraint(HttpMethod.Get)}
);

This is the angular call

app.factory('dataFactory', function ($http) {

    var factory = {};

    factory.data = function (callback) {
        $http.get('/api/movies').success(callback);
    };

    return factory;
});

I added this javascript just to rule-out angular, I get the same:

$.ajax({
url: "/api/movies",
type: 'GET',
//data: "{ 'ID': " + id + "}",
contentType: "application/json; charset=utf-8",
success: function(data) {
    alert(data);
},
error: function (xhr, ajaxOptions, thrownError) {
    alert(thrownError);
}
});

Any idea what I have done wrong?

2
In your MapHttpRoute shouldn't Api/ be all lowercase?jnthnjns
I got the routes from here, I dont think the case matters stackoverflow.com/questions/9499794/…Rob King
Can you post your code for the controller action method? Internal Server tells me it might be failing on the method when you make the ajax call. Maybe missing a parameter when you are making the call?zero7

2 Answers

0
votes

I assume your Web API and AngularJS app are running on a different port. In this case you are running in a Same-Origin-Policy issue.

Ensure your Web API is responding with HTTP CORS headers e.g.:

Access-Control-Allow-Origin: http://<angular_domain>:<angular_port>

or

Access-Control-Allow-Origin: *
0
votes

Doesn't look like a CORS issue to me as you are using a relative URL in your $.ajax() request.

Did you try $.getJSON("/api/movies").then(successHandler, faulureHandler)

Not sure of that will help but for one you are sending a contentType header with a GET request which contains no content. There should be an Accept header instead, but WebAPI should be fine without one.

I would also remove the constrains from the routing and revert back to the default route mapping to see if the problem is there.

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