patterncsharpMinor
Is this a good way to handle Web API UriTemplates?
Viewed 0 times
thishandleuritemplateswaywebgoodapi
Problem
I want to be able to do
But it seems clunky to me. Anyone have suggestions for a better way to do this?
/contacts/Matt%20Phillips and /contacts/1 and have both of them return a contact. The way I did that was to try and parse an int from the captured parameter and call the Id method instead of the byName method like so:[WebGet(UriTemplate="{param}"]
public Contact SingleParam(string param)
{
int x;
if (int.TryParse(param, out x))
{
return GetContactById(x);
}
else
{
return GetContactByName(param);
}
}
private Contact GetContactByName(string param)
{
var contact = from c in contacts
where c.Name.Equals(param)
select c;
if (!contact.Any())
{
return null;
}
return contact.Single();
}
public Contact GetContactById(int id)
{
var contact = from c in contacts
where c.ContactId == id
select c;
if (!contact.Any())
{
return null;
}
return contact.Single();
}But it seems clunky to me. Anyone have suggestions for a better way to do this?
Solution
There is an easier way. You can use uri templates to help you by making both handling methods operations.
If you do a GET on /contacts/Matt%20Phillips the second method will get invoked.
[ServiceContract]
public class ContactsApi
{
[WebGet(UriTemplate="{id}")]
public string GetById(int id)
{
//return by id
}
[WebGet(UriTemplate="{first} {last}")]
public string GetByName(string first, string last)
{
//return by name
}
}If you do a GET on /contacts/Matt%20Phillips the second method will get invoked.
Code Snippets
[ServiceContract]
public class ContactsApi
{
[WebGet(UriTemplate="{id}")]
public string GetById(int id)
{
//return by id
}
[WebGet(UriTemplate="{first} {last}")]
public string GetByName(string first, string last)
{
//return by name
}
}Context
StackExchange Code Review Q#3117, answer score: 3
Revisions (0)
No revisions yet.