Reputation: 2915
I have a small function in my web api controller that looks like this:
public IEnumerable<IEmployee> GetEmployeesByFullName(string firstName, string lastName)
{
var data = EmployeeDataProvider.GetEmployeeByFullName(firstName, lastName).ToList();
return data;
}
I would like to be able to call it, with blank values in either first or lastname, but I'm not really able to do so. I would like to simply do it in the URL.
Is it not possible to somehow send /GetEmployeesByFullName//Doe/
? Will I have to send it as post data, to send blank values?
If I do /GetEmployeesByFullName//Doe/
I am told there is no matching action, on the controller.
Setting the parameters to optional, in my route, doesn't seem to make any difference. I simply do not hit this function.
Upvotes: 1
Views: 3434
Reputation: 2684
As mostruash pointed out, you cannot do it with /GetEmployeesByFullName//Something
since MVC doesn't support having two optional parameters. Only the last parameter can be optional (see this stackoverflow question). If you want to do it by URL, why not simply state it as parameter:
/GetEmployeesByFullName?firstname=xxx&lastname=yyy
In this way, both can be empty:
/GetEmployeesByFullName?firstname=xxx // the method is called with lastname = null
/GetEmployeesByFullName?lastname=yyy // the method is called with firstname = null
If you have the use case that both parameters will be filled in, you could add the route like this:
routes.MapRoute(
name: "GetEmployees",
url: "GetEmployeesByFullName/{firstname}/{lastname}",
defaults: new { controller = "Default", action = "GetEmployeesByFullName", firstname = UrlParameter.Optional, lastname = UrlParameter.Optional }
);
Upvotes: 1