Get url parameters in NancyFx

馋奶兔 提交于 2019-12-03 14:25:31

问题


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


回答1:


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.




回答2:


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>();
}



回答3:


You can simply use:

var from = Request.Query.from;


来源:https://stackoverflow.com/questions/24189172/get-url-parameters-in-nancyfx

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!