Ananthan Unni
Ananthan Unni

Reputation: 1304

Call WebAPI method passing string id argument

I have an ASP.NET MVC4 WebAPI implementation in which I have a method to check if the username is available while signing up. When the user leaves the user name text box, an ajax call call will be posted to the server with the value in the text box.

I have implemented this as the following.

1) I have the WebAPI routing code set as...

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

2) I have the web api action to be called is written as...

    [HttpPost]
    public HttpResponseMessage IsUserNameAvailable(string id)
    {
        return Request.CreateResponse(HttpStatusCode.OK, (new UserManager()).IsUserNameAvailable(id));
    }

3) And my jquery call looks like the following...

    $.ajax({
        url: '/api/PublicServicesApi/IsUserNameAvailable',
        data: '{id:"testname"}',
        contentType: 'application/json; charset=utf-8',
        type: 'POST',
        success: function (d) {
            if (d == true)
               //NAME IS AVAILABLE
            else
                //NAME IS NOT AVAILABLE
        }
    });

But the problem is happening at the server

Upvotes: 1

Views: 6539

Answers (2)

Jon Susiak
Jon Susiak

Reputation: 4978

Change your routing to:

    config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{action}"
        );

Then change your action method to:

    [HttpPost]
    public HttpResponseMessage IsUserNameAvailable(dynamic value)
    {
        string id = value.id;
        return Request.CreateResponse(HttpStatusCode.OK, (new UserManager()).IsUserNameAvailable(id));
    }

Upvotes: 0

Olav Nybø
Olav Nybø

Reputation: 11568

You are including the action name in your URL, I think your routing should reflect this.

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

Upvotes: 1

Related Questions