Scottie
Scottie

Reputation: 11308

AJAX call can't find my WebAPI Controller

I have the following AJAX call:

var params = {
    provider: "facebook"
};

$.ajax({
    url: "http://localhost/taskpro/api/account/ExternalLogin",
    data: JSON.stringify(params),
    type: "POST",
    contentType: 'application/json; charset=utf-8'
})
.done(function (response) {
    alert("Success");
});

calling the following WebAPI controller:

public class AccountController : ApiController
{
    [HttpPost]
    [AllowAnonymous]
    public bool ExternalLogin(string provider)
    {
        return true;
    }
}

with the following routemap:

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

When I execute this, fiddler is returning:

{"Message":"No HTTP resource was found that matches the request URI 
'http://localhost/taskpro/api/account/ExternalLogin'.","MessageDetail":
"No action was found on the controller 'Account' that matches the request."}

I have several other calls being made to this controller that are working just fine. It's just THIS call that is giving me troubles.

Also, if I remove the parameter in the controller so it's just

public bool ExternalLogin()

and comment out the data line in the ajax, it works fine.

Any ideas why the routing is not working for this call?

Upvotes: 1

Views: 1701

Answers (1)

Scottie
Scottie

Reputation: 11308

I ran across this article:

http://encosia.com/using-jquery-to-post-frombody-parameters-to-web-api/

Basically, WebAPI can't bind to primitive data types like string. You have to either create a model to bind to, or use the [FromBody] attribute. I modified my method to this:

public bool ExternalLogin([FromBody]string provider)

and it's working fine now.

Upvotes: 2

Related Questions