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; }
}
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With