Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get url parameters in NancyFx

Tags:

nancy

I am using NancyFx to build a web API, but I am facing some problems when getting parameters from the URL.

I need to send, to the API, the request .../consumptions/hourly?from=1402012800000&tags=%171,1342%5D&to=1402099199000 and catch the value of the parameters: granularity, from, tags and to. I tried several approches and none worked. I tried, for example,

Get["consumptions/{granularity}?from={from}&tags={tags}&to={to}"] = x => {     ... } 

How can I do this?

Luis Santos

like image 460
user3734857 Avatar asked Jun 12 '14 16:06

user3734857


People also ask

How can I get parameters from a URL string?

The parameters from a URL string can be retrieved in PHP using parse_url() and parse_str() functions. Note: Page URL and the parameters are separated by the ? character. parse_url() Function: The parse_url() function is used to return the components of a URL by parsing it.

How do I get URL parameters in Drupal 7?

In an ideal scenario, you should use a callback function in a menu and named arguments. But in case you're in a really particular scenario and need to get arguments like this, you can do it using the arg() function. $category = arg(0); $brand = arg(1);

Is GET parameters are included in URL?

GET parameters (also called URL parameters or query strings) are used when a client, such as a browser, requests a particular resource from a web server using the HTTP protocol. These parameters are usually name-value pairs, separated by an equals sign = . They can be used for a variety of things, as explained below.


2 Answers

There are 2 things that you are trying to get from the URL. One is a part of the path hourly - and the other is the parameters in the query string - namely the values for from and to.

You can get to the part of the path through the parameter to the handler - the x in your example.

You can get to the query string through the Request which is accessible on the NancyModule.

To put this in code:

Get["consumptions/{granularity}"] = x => {     var granularity = x.granularity;     var from = this.Request.Query["from"];     var to = this.Request.Query["to"]; } 

The variables granularity. from, and to are all dynamic, and you may need to convert them to whatever type you want.

like image 135
Christian Horsdal Avatar answered Oct 18 '22 11:10

Christian Horsdal


You can let NancyFx's model binding take care of the url query string.

public class RequestObject  {     public string Granularity { get; set; }     public long From { get; set; }     public long To { get; set; } } 

/consumptions/hourly?from=1402012800000&to=1402099199000

Get["consumptions/{granularity}"] = x => {     var request = this.Bind<RequestObject>(); } 
like image 22
feltocraig Avatar answered Oct 18 '22 10:10

feltocraig