Click here to Skip to main content
15,881,831 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
I am calling Asp.net web api Post methos which has one parameter named value of type string.

Code as below:

In ValueController:

SQL
public IHttpActionResult Post(string value)
      {
          return Created(Request.RequestUri + "/" + "id=5", value);
      }


C#
Jquery Calling Web Api:


C#
$.ajax({
                    url: 'http://localhost:63022/api/values',
                    type: 'POST',
                    data: '{"value":"ravi"}',
                    contentType: "application/json;charset=utf-8",
                    crossDomain : true,
                    success: function (data) {
                        alert('success');
                    },
                    error: function (x, y, z) {
                        alert('error');
                    }
                });


Question 1:
When I run this code and call web api Post method using above jquery ajax call, I get Http error 405 method not allowed.

Question 2:
C#
Modification in ValueController, adding FromBody attribute


C#
public IHttpActionResult Post([FromBody]string value)
       {
           return Created(Request.RequestUri + "/" + "id=5", value);
       }



When I run this code and call web api Post method using above jquery ajax call, I get null in string value action method parameter [Post([FromBody]string value)].

Is it mandatory to write FromBody attribute for Post method to work in Question 1?

Guys please help me out for question 1 and 2...
Posted
Updated 6-Sep-18 6:56am
v3

This is how I ususaly write my web api

C#
[HttpPost]
[Route("api/home/activity/{activityID}")]
public object getComments(long activityID)
{

          //Search by activityID code will be here
       // return new { status = !hasError ? "Success" : "Fail" };
}
 
Share this answer
 
Try adding the [HttpPost] attribute to your function.
 
Share this answer
 
Sometimes including next code in the controller file is useful:

C#
public HttpResponseMessage Options()
{
   return new HttpResponseMessage { StatusCode = HttpStatusCode.OK };
}
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900