mdelvecchio
mdelvecchio

Reputation: 627

pass in extra parameters to Web API 2 method

I've got a Web API 2 method like so:

[Route("api/notifications/{username}")] //attribute routing, new in Web API 2
//[HttpGet]
public IEnumerable<Notification> GetNewNotifications(string username)
{
    return Notification.GetNewNotifications(username);
}

...which I consume in javascript w/ jquery like so:

$.getJSON('/api/notifications/' + username)

Which works fine. But what is the correct way to pass in addition arguments? I've seen different answers and it's unclear to me. I don't think I want to pass in them in via forward-slashes because they aren't hierarchical in nature. Normally I'd do this w/ querystring params, but I don't know how to pick them up in the server-side.

thanks!

Upvotes: 1

Views: 743

Answers (1)

James
James

Reputation: 82096

Generally the recommended approach is to append additional arguments to the query string

/api/notifications/{username}?sent=true&received=false

QueryString parameters are handled just the same as POST parameters when it comes to the data binding therefore all you need to do is specify them in your action signature e.g.

public IEnumerable<Notification> GetNewNotifications(string username, bool sent = false, bool received = false)
{
    ....
}

However, depending on the type of information it may be more appropriate as a HTTP Header or alternatively you could define specific URLs which you map internally

/api/notifications/{username}/pending 

Upvotes: 2

Related Questions