1

I have ASP.Net MVC4 WEB API, hosted in local IIS. I request the api from android using GET method. Response is 405 Action not Allowed.

I Have This Method in Controller :

    public IEnumerable<Table> GET()
    {
        return _repository.GetAll();
    }

But When I Change the Method to POST:

    public IEnumerable<Table> POST()
    {
        return _repository.GetAll();
    }

and request from android with POST method.

I got the RESULTS.

I request both GET and POST with the same route.

'/api/tables'

In android project, I use HttpUrlConnection to request API.

try{
            URL url = new URL(urls[0]);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setReadTimeout(5000 /* milliseconds */);
            conn.setConnectTimeout(7500 /* milliseconds */);
            conn.setRequestProperty("Accept", "application/json");
            conn.setRequestMethod(method);
            conn.setDoInput(true);

            if(method == "POST")
                conn.setDoOutput(true);

            if(params != null){
                // Get OutputStream for the connection and 
                // write the parameter query string to it
                OutputStream os = conn.getOutputStream();
                BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
                writer.write(getURLEncodedString(params));
                writer.flush();
                writer.close();
            }

            // Starts the query
            conn.connect();

What am i doing wrong?

info:

when request from browser Get Method return results and Post Method 405.

2 Answers2

1

The problem is in my android project

Android Developer: HttpUrlConnection

HttpURLConnection uses the GET method by default. It will use POST if setDoOutput(true) has been called.

stackoverflow: https://stackoverflow.com/questions/8187188/android-4-0-ics-turning-httpurlconnection-get-requests-into-post-requests

Community
  • 1
  • 1
0

May be it's a routing issue. Make some little changes in your WebApi.config of webapi

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

One more important thing here is that with this style of routing, you must use attributes to specify the allowed HTTP methods (like [HttpGet]).

Ankush Jain
  • 5,654
  • 4
  • 32
  • 57