Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET WebApi Post Method - 404 When Passing Parameters

I cannot for the life of me figure this out. I have a web api controller with Get and Post methods. The Get method works fine with and without parameters, but the post breaks when I try to add a String parameter to it. Below is my code.

Route:

        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "{controller}/{id}",
            defaults: new { id = UrlParameter.Optional }
        );

Controller:

public class AuditController : ApiController
{
    public String Post(String test)
    {
        return "Success : " + test;
    }

    public String Get(String test)
    {
        return "Success : " + test;
    }
}

Request:

    var request = WebRequest.Create("http://localhost:42652/Audit");
        request.Method = "POST";
        request.ContentType = "application/x-www-form-urlencoded";
        using (var writer = new StreamWriter(request.GetRequestStream()))
        {
            writer.Write("test=TEST");
        }
        WebResponse webResponse = request.GetResponse();

I've tried many variations on the request, I feel like there's something simple I'm missing. Thanks for your help.

like image 343
Jonesopolis Avatar asked Jun 11 '13 15:06

Jonesopolis


2 Answers

Since you are expecting parameter test to come from body of a request, you would need to decorate it with FromBody attribute. Example: ([FromBody]String test). This is not true for other complex types, for example: Employee class which is implicitly considered to be coming from Body.

Rearding GET request. It should be working only with test coming from query string /Audit?test=Mike

Following blog post has more details about parameter binding: http://blogs.msdn.com/b/jmstall/archive/2012/04/16/how-webapi-does-parameter-binding.aspx

Also, I see that you are using WebRequest. Have you considered using HttpClient from System.Net.Http instead?

like image 174
Kiran Avatar answered Oct 23 '22 23:10

Kiran


Change your AuditController to include the FromBody attribute :

public class AuditController : ApiController
{
    public String Post([FromBody]String test)
    {
        return "Success : " + test;
    }

    public String Get(String test)
    {
        return "Success : " + test;
    }
}

cf. http://msdn.microsoft.com/en-us/library/system.web.http.frombodyattribute(v=vs.108).aspx

like image 3
adhocgeek Avatar answered Oct 23 '22 23:10

adhocgeek