I wrote a REST web service in C#. Get request works fine, but insert, update and delete not.
When I try to insert some values from an Android tablet (client) via the REST service into a mySQL database an error occurs: Method not allowed
I send a JSON string from the android client to the web service:
in Android Developer Tool (eclipse):
String url = IP + PORT +"/RESTService/insert/";
HttpClient client = new DefaultHttpClient();
HttpResponse response;
JSONObject json = new JSONObject();
HttpPost post = new HttpPost(url);
json.put("userName", name);
json.put("userPassword", password);
StringEntity se = new StringEntity(json.toString());
se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE,"application/json"));
post.setEntity(se);
response = client.execute(post);
in C#:
Service interface:
[OperationContract]
[WebInvoke(Method = "POST", UriTemplate = "/insert/{jsonObj}",
RequestFormat = WebMessageFormat.Json,
ResponseFormat = WebMessageFormat.Json,
BodyStyle = WebMessageBodyStyle.Bare)]
void InsertUser(string jsonObj);
Service methode:
public void InsertUser(string jsonObj)
{
string name = null;
string password = null;
DataContractJsonSerializer obj = new DataContractJsonSerializer(typeof(User));
dynamic dynObj = JsonConvert.DeserializeObject(jsonObj);
foreach (var data in dynObj.userObject)
{
name = data.userName;
password = data.userPassword;
}
string sql = "INSERT INTO user (userName, userPassword) VALUES('" + name + "', '" + password +"';)";
if (conn.State == ConnectionState.Closed)
{
conn.Open();
}
command = new MySqlCommand(sql, conn);
command.ExecuteNonQuery();
conn.Close();
command.Dispose();
}
My User:
namespace RESTService
{
[DataContract]
public class User
{
[DataMember]
public string userName { get; set; }
[DataMember]
public string userPassword { get; set; }
public User(string name, string password)
{
this.userName = name;
this.userPassword = password;
}
}
When I start the web service and try to insert the values via android app, nothing happens. I think, that the values from the app don't reach the web service. But I have no idea why.
It would be great, if somebody can help me :).
Thanks in advance
解决方案
The first step would be to write a C# unit test that exercises the InsertUser method through the web service. When running this test I think you'd discover that your UriTemplate is incorrect. If you're making a POST, the json object will be in the body of the request, not in the url. I'd try an attribute like this:
[WebInvoke(Method = "POST", UriTemplate = "/users",
RequestFormat = WebMessageFormat.Json,
ResponseFormat = WebMessageFormat.Json]
Your android url would look like this (I think):
String url = IP + PORT + "/users";
Another thing to check out would be Fiddler. When your unit test passes, you can inspect successful requests. Your android client can also be configured to use Fiddler.