Create Web API with Post method in ASP Net MVC Part | 6

preview_player
Показать описание
Here you can learn how to Create Web API with Post method in ASP.Net MVC

Requirement: Visual studio 2015, MVC 5, SQL server 2012 or higher version

We use here Attribute Routing

1) [RoutePrefix("api/employee")] in top of controller

2) [Route("Add")] on top of action method where you want to access using this.

Now let us start the creation of web API Post Method WITH THE help of ASP.NET MVC:

CREATE TABLE [employees](
[empid] [bigint] NOT NULL,
[Name] [nvarchar](500) NULL,
[salary] [float] NULL,
PRIMARY KEY CLUSTERED
(
[empid] ASC
)
) ON [PRIMARY]

Plan to insert new record of an employee in the table employees
Like empid=120, Name=Alen, Salary 25000

Here we define the Post method to insert the records in the database:

Create a Model Class:
public class employee
{
public long empid { get; set; }
public string Name { get; set; }
public Nullable salary { get; set; }
}

[Route("Add")]
[HttpPost]
public IHttpActionResult AddEmployee(employee emp)
{

string json;
SampleEntities db = new SampleEntities();

db.SaveChanges();

json = JsonConvert.SerializeObject(emp);
var response = this.Request.CreateResponse(HttpStatusCode.Created);
response.Content = new StringContent(json, Encoding.UTF8, "application/json");
return ResponseMessage(response);

}

JSON.NET: Json.NET is a third-party library that helps conversion between JSON text and .NET object using the JsonSerializer.

Serialization is the process of converting . NET objects such as strings into a JSON format and deserialization is the process of converting JSON data into . NET objects

JSON DATA need to be insert

{
"empid": 121,
"Name": "John",
"salary": 10000
}
Рекомендации по теме