How to Create Web API in ASP Net MVC with HTTPGET Method Part | 5

Опубликовано: 12 Октябрь 2024
на канале: Syed Ali
914
17

Here you can learn How to create Web API in ASP.Net MVC with HTTPGET method

The ASP.NET Web API is a framework that makes it easy to build HTTP services that reach a broad range of clients, including browsers, mobile devices AND Desktop PC and tablets require services.


The HTTP actions and their corresponding CRUD operations are:

GET (Read)
Retrieves the representation of the resource.

PUT(Update)
Update an existing resource.

POST (Create)
Create new resource.

DELETE (Delete)
Delete an existing resource.

Add a decorating method with attributes to make it easy to do CRUD operations.

[HttpGet]
[HttpPost]


Attribute Routing in ASP.NET Web API 2:

Routing is how Web API matches a URI to an action. Web API 2 supports a new type of routing, called attribute routing. As the name implies, attribute routing uses attributes to define routes. Attribute routing gives you more control over the URIs in your web API. For example, you can easily create URIs that describe hierarchies of resources.

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

2) [Route("list")] on top of action method where you want to access

AND Final url would be http://localhost:58988/ api/employee/list


Return JSON instead of XML in ASP.NET Web API when using Chrome
In file App_Start / WebApiConfig.cs
config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/html"));

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

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

Here we define the get method to retrieve the records from the database:


[RoutePrefix("api/employee")]
public class EmployeeController : ApiController
{
[Route("list")]
[HttpGet]
public IHttpActionResult get()
{
string json;
SampleEntities db = new SampleEntities();
var result = db.employees.ToList();
json = JsonConvert.SerializeObject( result);
// json = JsonConvert.SerializeObject(new { Employee = result });
var response = this.Request.CreateResponse(HttpStatusCode.OK);
response.Content = new StringContent(json, Encoding.UTF8, "application/json");
return ResponseMessage(response);
}
}

Note: IHttpActionResult – new way of creating responses in ASP.NET Web API 2

IHttpActionResult allows developers to enhance their Web API code to be :

More testable.
More reusable.
Cleaner, and more elegant.

And Return JSON Below like:

[
{
"empid": 101,
"Name": "John",
"salary": 10000
},
{
"empid": 102,
"Name": "Adam",
"salary": 12000
},
{
"empid": 103,
"Name": "Maria",
"salary": 15000
}
]


Other Example:
[Route("list1")]
[HttpGet]
public IHttpActionResult get1()
{
SampleEntities db = new SampleEntities();

var result = db.employees.ToList();

if (result == null)
return NotFound();

return Ok(result);
}



The above code looks simpler than the HttpResponseMessage example and hides the lower level http message construction away from your controller.

There are some predefined helper methods for IHttpActionResult are:

Ok : Returns an HTTP 200 (“OK”)
Redirect : Returns an HTTP 302 (“Found”)
NotFound : Returns an HTTP 404 (“Not Found”)
Unauthorized : Returns an HTTP 401 (“Unauthorized)
Conflict : Returns an HTTP 409 (“Conflict”)
BadRequest : Returns an HTTP 400 (“Bad Request”)