指定REST服务中传递参数的方式

时间:2018-06-15 13:58:03

标签: c# rest

我打算使用C#创建一个REST服务,但是如何构建它有点困惑。

在这个基本示例中,有一种方法应该编写TimeSeries数据。根据我所做的研究,我希望网址类似于:http://myserver/v1/TimeSeries/ {id}

示例:http://myserver/v1/timeseries/1 {[ “20180101”, “10”] [ “20180102”, “20”]}

在此示例中,TimeSeries ID为1,JSON(可能不正确的JSON,但说明示例)表示要写入的数据点。

因此要写入的时间序列的ID在URI中。要写入的实际数据将在请求正文中(作为JSON发布)。

这是我到目前为止所拥有的:

[ServiceContract]
public interface ITimeSeriesService
{
    [OperationContract]
    [WebInvoke(Method = "PUT", UriTemplate = "timeseries", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)]
    string WriteTimeSeries(int id, string datapoints);

}

所以我的问题是:

  • 如何将方法绑定到URI,如上所述?
  • 如何指定参数'id'在URI中,而'datapoints'在正文中?

我正在使用.Net 4.5.2

感谢您的帮助。

1 个答案:

答案 0 :(得分:1)

JSON只是一个字符串表示,表示面向对象语言中的内容及其属性和字段。

例如在C#中,你可能有一个类:

Animal
{
   public string Breed {get; set:}
   public int Age {get; set;}
}

将动物传递给您的(假设Web API)控制器方法的JSON如下所示:

{"Animal":{"Breed":"Bull Dog", "Age":"5"}}

并在使用默认路由({controller}/{action})的WebAPI控制器中,您的方法如下所示:

public string AddDog([FromBody]Animal animal)
{
   // do stuff with animal
}

最有可能的是,我希望在请求正文中使用JSON的POST方法。 WebAPI / MVC将尝试根据与请求最匹配的方法来路由方法。

URL /查询类似于:

 http://myApp:4000/Animal/Add

当然,如果您构建它以与其他.NET App一起使用,那么您只需使用HttpClient。该代码看起来很像:

// .net core 2 with extensions
var Client = new HttpClient();
var message = client.PostAsJsonAsync("http://myApp:4000/Animal/Add", myAnimalObject).GetAwaiter().GetResult();
相关问题