Am trying to post json data to the server. am using visual studio 2012 RC and windowsazure for hosting the web application . On posting am getting the following errors :
-
OPTIONS http://*.azurewebsites.net/api/Child 405 (Method Not Allowed) jquery-1.7.1.js:8102
-
XMLHttpRequest cannot load http://*.azurewebsites.net/api/Child. Origin null is not allowed by Access-Control-Allow-Origin.
My client side code is :
function PostChild() {
var Chld = {};
Chld.Child_FirstName = $("#Child_FirstName").val();
Chld.Child_LastName = $("#Child_LastName").val();
Chld.Child_Age = $("#Child_Age").val();
var createurl = "http://*.azurewebsites.net/api/Child";
$.ajax({
type: "POST",
url: createurl,
contentType: "application/json; charset=utf-8",
data: JSON.stringify(Chld),
statusCode: {
200: function () {
$("#txtmsg").val("done");
alert('Success');
}
},
error:
function (res) {
alert('Error');
$("#txtmsg").val("error" + " "
+ res.status + " " + res.statusText);
}
});
}
My server side code is :
public HttpResponseMessage PostChild(Child child)
{
if (ModelState.IsValid)
{
db.Children.Add(child);
db.SaveChanges();
HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.Created, child);
response.Headers.Location = new Uri(Url.Link("DefaultApi", new { id = child.ChildID }));
return response;
}
else
{
return Request.CreateResponse(HttpStatusCode.BadRequest);
}
}
Help me please
Thanks,
The errors was due to CORS (Cross Origin Resource sharing). By default, a web page cannot make calls to services (APIs) on a domain other than the one where the page came from. This is a security measure to avoid cross-site forgery attacks and all.
To solve it follow this tutorial:
http://blogs.msdn.com/b/carlosfigueira/archive/2012/02/20/implementing-cors-support-in-asp-net-web-apis.aspx