Udostępnij za pośrednictwem


Using Azure MobileServiceClient throws "The request could not be completed. (Method Not Allowed)" exception

In case anyone else runs into this:

I'm working with the Microsoft.WindowsAzure.MobileServices.MobileServiceClient class, trying to call a mobile API I've set up in--where else--an Azure Mobile Service instance.

My call looks something like this:

JToken response = await _mobileClient.InvokeApiAsync("myapimethodname");

 

And I'm trying to call an API containing pretty standard Node.js script that starts out like this:

 

var azure = require('azure')
  , qs = require('querystring');

/* Issued by Raspberry Pi:
    https://[blank].azure-mobile.net/api/photos
With headers = "X-ZUMO-APPLICATION: [mobile_services_app_key]"
    Header contains the application key
*/

exports.get = function(request, response) {

 

Now, I've already successfully used this API using an HttpWebRequest and some code like this:

WebRequest r = WebRequest.Create("https://full_api_url_here");

r.Method = "GET";

r.Headers.Add("X-ZUMO-APPLICATION", "mobile_service_api_key_here");

 

using (var responseStream = r.GetResponse().GetResponseStream()) {

StreamReader sr = new StreamReader(responseStream);
string data = sr.ReadToEnd();

}

 

The point is, I know the API call works, and I figured using the MobileServiceClient class would be a lot easier and cleaner. But I'm getting this odd error.

I do a little Binging and find this bit of Azure Mobile Services documentation that states:

How to: Implement HTTP methods

A custom API can handle one or more of the HTTP methods, GET, POST, PUT, PATCH, and DELETE. An
exported function is defined for each HTTP method handled by the custom API. A single custom API code
file can export one or all of the following functions:

   
exports.get = function(request, response) { ... };
exports.post = function(request, response) { ... };
exports.patch = function(request, response) { ... };
exports.put = function(request, response) { ... };
exports.delete = function(request, response) { ... };

The custom API endpoint cannot be called using an HTTP method that has not been implemented in the
server script, and a 405 (Method Not Allowed) error response is returned. Separate permission levels can
be assigned to each support HTTP method.

 

The highlights are mine, so take note. I then look up documentation on the MobileServiceClient class and find this:

InvokeApiAsync(String)

Invokes a user-defined custom API of a Windows Azure Mobile Service using an HTTP POST.

 

Again, the highlights are mine. Interesting.  

Finally, looking back at my script, I realize I've only implemented GET functionality.

 

Bingo.

 

My solution? I changed the API code like so:

function myApi(request, response) {

...

}

exports.get = myApi;
exports.post = myApi;

 

Pretty? No. But it works and it's resulted in much simpler code.