user1263981
user1263981

Reputation: 3157

How to pass an object of type as a parameter to Web Api Get/Post method

Here is my Post method and i am passing an object which contains parameters

public class TransactionController : ApiController
{
 [HttpPost]
    public TransactionResponse mytest2(TransactionOperationInput input)
    {
       // some operation here 
    }
}

Here is the URL i am trying to test

http://localhost:33755/api/Transaction/mytest2?SourceKey=abcdef&Pin=123&Criteria=2018-09-12 00:00:00

Outcome When method is set to POST and Get

[HttpPost] : I get an error 405 method not allowed.

[HttpGet] : input parameter is NULL

This is the Register Route class; ( sorry i am new to Route tables)

public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

        routes.MapRoute(
            name: "Default",
            url: "{controller}/{action}/{id}",
            defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
        );
    }

Do i need to update route table? or Is my URL wrong?

Also, should i have the service method as Post or Get?

Upvotes: 0

Views: 2568

Answers (1)

user3559349
user3559349

Reputation:

You cannot navigate to a [HttpPost] method, so it needs to be a [HttpGet]. And to bind to a complex object from query string values, you need to use the [FromUri] attribute

[HttpGet] // can be omitted 
public TransactionResponse mytest2([FromUri]TransactionOperationInput input)

For more information on parameter binding in web-api, refer Parameter Binding in ASP.NET Web API.

Upvotes: 1

Related Questions