1
votes

I have implemented ASP.NET WebApi and consumed in Android application with HTTPPOST. Parameter less methods are calling perfectly but method with parameters not working while it is working fine with Advanced Rest Client in Google Chrome also working perfectly with HTTP GET.

Caller Code in Android:

String url = "http://192.168.15.3/api/user"    

HttpPost postMethod = new HttpPost(url);

postMethod.setHeader("Content-Type", "application/json; charset=utf-8");
postMethod.setHeader("Accept", "*/*");
postMethod.setHeader("Accept-Encoding", "gzip, deflate");
postMethod.setHeader("Accept-Language", "en-US,en;q=0.8");

List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("id", "1"));

DefaultHttpClient hc = new DefaultHttpClient();         
HttpResponse response;
postMethod.setEntity(new UrlEncodedFormEntity(nameValuePairs, "UTF-8"));
response = hc.execute(postMethod);
HttpEntity entity = response.getEntity();               
InputStream inStream = entity.getContent();
String result = convertStreamToString(inStream);
Log.e("Result: ", result);              

Controller:

public class UserController : ApiController
{
    UserCredentials[] users = new UserCredentials[] 
    { 
        new UserCredentials { User_ID = "1", User_Name = "testuser", Password = "test", First_Name = "Test", Last_Name = "User",
                              Email = "[email protected]", Phone ="123456789", Mobile = "123456789", User_Type = "user" }, 
        new UserCredentials { User_ID = "2", User_Name = "testuser2", Password = "test", First_Name = "Test", Last_Name = "User",
                              Email = "[email protected]", Phone ="123456789", Mobile = "123456789", User_Type = "user" }
    };

    [AcceptVerbs("POST")]
    public IEnumerable<UserCredentials> GetAllUsers()
    {
        return users;
    }

    [AcceptVerbs("POST")]
    public IHttpActionResult GetUser(string id)
    {
        var user = users.FirstOrDefault((p) => p.User_ID.Equals(id));
        if (user == null)
        {
            return NotFound();
        }
        return Ok(user);
    }
}

Error: {"Message":"No HTTP resource was found that matches the request URI 'http://192.168.15.3/api/user'.","MessageDetail":"No action was found on the controller 'User' that matches the request."}

1
can you please post your complete webapi controller code?Mukesh Modhvadiya
@MukeshModhvadiya Added. It is also working fine with HTTP GET.Rehman Zafar

1 Answers

0
votes

It is throwing an error because your controller does not have any matching httppost method. You are trying to post data to method which accepts GET request.

WebApi works on convention based method names. Your methods starts with "Get" so it will map requests in below manner :

Get All users - GET - /api/users Get user by Id - GET - /api/users/id

So you can call them using HttpGet request and not POST.