Reputation: 3185
I have created a controller in the ASP.NET Web API. Below is the code for the controller
public class CalculateController : ApiController
{
public IEnumerable<string> Get()
{
return new string[] { "from get method" };
}
public IEnumerable<string> Post([FromBody]string value)
{
return new string[] { "from post method" };
}
}
Below is the code that I am using to make a post request to the webAPI
HttpWebRequest httpWReq = (HttpWebRequest)WebRequest.Create("http://localhost:62479/api/calculate");
StringBuilder postdata = new StringBuilder("value=Anshuman");
byte[] data = Encoding.UTF8.GetBytes(postdata.ToString());
httpWReq.Method = "POST";
httpWReq.ContentType = "application/x-www-form-urlencoded";
httpWReq.ContentLength = data.Length;
using (Stream stream = httpWReq.GetRequestStream())
{
stream.Write(data, 0, data.Length);
}
HttpWebResponse response = (HttpWebResponse)httpWReq.GetResponse();
string responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();
The problem is that even if I make a POST request even then the data is returned from the GET method of the Controller. I have not made any changes in the default configuration of the Web API project. I am using MVC 4.
Thanks for your time. If any other information is required then please add a comment.
I have both the projects running in Visual Studio 2012 on the same machine.
Upvotes: 0
Views: 1846
Reputation: 8539
your post method without parameters.
by default it looks like this:
public void Post([FromBody]string value)
{
//do something with data you posted
}
in your case, if you want return some string data:
public IEnumerable<string> Post([FromBody]string value)
{
return new string[] { "from post method" };
}
Just tested your code. It works fine, and post method hitted correctly. But in my case i got this in WebApiCOnfig.cs. It helps to make web api routing more flexible.
config.Routes.MapHttpRoute(
name: "DefaultApiWithId",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional },
constraints: new { id = @"\d+" }
);
config.Routes.MapHttpRoute(
name: "DefaultApiWithAction",
routeTemplate: "api/{controller}/{action}"
);
config.Routes.MapHttpRoute("DefaultApiGet", "api/{controller}", new { action = "Get" }, new { httpMethod = new HttpMethodConstraint(HttpMethod.Get) });
config.Routes.MapHttpRoute("DefaultApiPost", "api/{controller}", new { action = "Post" }, new { httpMethod = new HttpMethodConstraint(HttpMethod.Post) });
config.Routes.MapHttpRoute("DefaultApiPut", "api/{controller}", new { action = "Put" }, new { httpMethod = new HttpMethodConstraint(HttpMethod.Put) });
config.Routes.MapHttpRoute("DefaultApiDelete", "api/{controller}", new { action = "Delete" }, new { httpMethod = new HttpMethodConstraint(HttpMethod.Delete) });
Upvotes: 3
Reputation: 36
You can add HttpPost and HttpGet action attributes to the relevant actions which will restrict the post from being directed to the get action by the routes
Upvotes: 0