Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating POST method in Web API

I'm developing a web service, using WEB .API. I'm following the example, which include:

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

for creating a POST method, allowing a client to send data in POST in ordert to insert these data in the database (I'm using Entity Framework).

What I want do, however, is slightly difference, since the data I want pass in post to the web service are not associated to any object of database: I have some data that should be write in more then one table. For example:

{"activity":"sport","customValue":"22","propertyIndex":"122-x"}

The activty value (sport) should be writed on one table, while the others two parameters (customValue e properyIndex) shouldbe writed on another table.

So I think I need to parse the json file received in POST and then execute the two insert operation.

How can I perform this task?

like image 205
GVillani82 Avatar asked Aug 09 '26 02:08

GVillani82


1 Answers

You need to create an object in web API project with Activity, CustomValue, PropertyIndex properties:

  public class MyTestClass
  {
      public string Activity { get; set; }
      public string CustomValue { get; set; }
      public string PropertyIndex { get; set; }
  }

and HttpPost will be:

  [HttpPost]
  public HttpResponseMessage Post(MyTestClass class)
  {
      // Save Code will be here
      return new HttpResponseMessage(HttpStatusCode.OK);
  }     
like image 58
Yousuf Avatar answered Aug 10 '26 15:08

Yousuf