Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using optional complex type action parameter for a POST Web API

I am trying to write an API with the following prototype:

[HttpPost]
public ApplicationStatus appLogIn(string id, UserCredentials userCredentials = null)

But when I make a request to this API, with or without userCredentials, I get the following error with response code as 500

{
  "Message": "An error has occurred.",
  "ExceptionMessage": "Optional parameter 'userCredentials' is not supported by 'FormatterParameterBinding'.",
  "ExceptionType": "System.InvalidOperationException",
  "StackTrace": null
}

If I do not make the userCredentials as optional, everything works fine. The userCredential definition is as follows:

public class UserCredentials
{
    public string password { get; set; }
    public string username { get; set; }
}
like image 929
labyrinth Avatar asked May 25 '15 10:05

labyrinth


People also ask

How do you pass complex objects to Web API post?

Best way to pass multiple complex object to webapi services is by using tuple other than dynamic, json string, custom class. No need to serialize and deserialize passing object while using tuple. If you want to send more than seven complex object create internal tuple object for last tuple argument.

How do I pass optional parameters in Web API?

Optional Parameters in Web API Attribute Routing and Default Values: You can make a URI parameter as optional by adding a question mark (“?”) to the route parameter. If you make a route parameter as optional then you must specify a default value by using parameter = value for the method parameter.

How do I pass multiple parameters to Web API controller methods?

Step1: Create a Blank Solution called WebAPI-Multiple-Objects as shown below. Add a new class library project (Model) into it and create two classes named Product, Supplier. Now, on the API controller side, you will get your complex types as shown below.


1 Answers

Try changing the API definition to:

[HttpPost]
public ApplicationStatus appLogIn(string id, UserCredentials userCredentials)

As UserCredentials is a reference type, if client doesn't provide a value it will be set to null

like image 116
sree Avatar answered Oct 04 '22 21:10

sree