在Web API中创建POST方法

GVi*_*i82 3 .net c# json asp.net-web-api

我正在使用WEB .API开发Web服务.我正在关注这个例子,其中包括:

public HttpResponseMessage PostProduct(Product item)
{
    item = repository.Add(item);
    var response = Request.CreateResponse<Product>(HttpStatusCode.Created, item);

    string uri = Url.Link("DefaultApi", new { id = item.Id });
    response.Headers.Location = new Uri(uri);
    return response;
}
Run Code Online (Sandbox Code Playgroud)

用于创建POST方法,允许客户端在ordert中的POST中发送数据以将这些数据插入数据库中(我正在使用实体框架).

但是,我想要做的是略有不同,因为我希望传递给Web服务的数据不与数据库的任何对象相关联:我有一些数据应该写在多个表中.例如:

{"activity":"sport","customValue":"22","propertyIndex":"122-x"}
Run Code Online (Sandbox Code Playgroud)

激活值(运动)应该写在一个表上,而其他两个参数(customValue e properyIndex)应该写在另一个表上.

所以我认为我需要解析POST中收到的json文件然后执行两个插入操作.

我该如何执行此任务?

You*_*suf 8

您需要在Web API项目中使用Activity,CustomValue,PropertyIndex属性创建一个对象:

  public class MyTestClass
  {
      public string Activity { get; set; }
      public string CustomValue { get; set; }
      public string PropertyIndex { get; set; }
  }
Run Code Online (Sandbox Code Playgroud)

和HttpPost将是:

  [HttpPost]
  public HttpResponseMessage Post(MyTestClass class)
  {
      // Save Code will be here
      return new HttpResponseMessage(HttpStatusCode.OK);
  }     
Run Code Online (Sandbox Code Playgroud)