×

iFour Logo

Building A Restful API in ASP.NET MVC 5

Kapil Panchal - June 09, 2021

Listening is fun too.

Straighten your back and cherish with coffee - PLAY !

  • play
  • pause
  • pause
Building A Restful API in ASP.NET MVC 5

In ASP.NET MVC architecture, when the request comes to our application, MVC Framework drops this request to action in a controller, this action returns the view most of the time which is then analyzed by the razor view engine, and finally, the HTML markup is returned to the client. So, HTML tagging is generated on the server and then sent back to the client in this approach.

 

Table of Content

There is another way of generating the HTML tag, we can generate it on the client. This way, instead of sending back HTML tags, they can return raw data.

What is the benefit of this approach?


  • It requires fewer server resources (it potentially enhances the scalability of the application because each client will be responsible to generate its views).
  • Raw data frequently needs less bandwidth than HTML markup. This allows data to potentially arrive more quickly to the customer. And this may improve the perceived efficiency of the app.
  • This approach supports a wide range of customers like mobile applications and tablets.

These applications are simply referred to as endpoints that get the data and generate the local view. We refer to these terminals as Data Services (Web APIs) because they only return data and not tags.

Get a quote for top-notch API Integration Services!


Web APIs are not only limited to cross-peripherals, they are also widely used in our web applications to add new functionality. Many popular sites such as Youtube, Facebook, and Twitter display public data services that we may consume in our web apps. We can merge their data into our app and provide new experiences for the new user. Those are the good things.

Restful Convention


So, you know what HTTP services and the web API are. Here, we are going to develop an application that supports a few various types of requests.

GET /API/students (to get the list of students)

GET /API/students/1 (to get the single student)

POST /API/students (to add the student and add the students' data in

Don't confuse GET and POST data requests, we use get request to get a list of resources or data.

And we use post requests for creating the new one.

Now, for updating the student, we use the PUT application.

PUT /API/customers/1

This way the client id is in the URL and the data or properties to be updated will be in the body of the request. And lastly, remove the student.

Delete /API/customers/1

We send the HttpDelete request to the endpoint. So what you see here, in terms of request types and parameters is a standard convention mentioned for requesting REST (Representational State Transfer)

Step 1

First, create an ASP.NET Web application project in Visual Studio and call it RestAPI. You can do this by selecting File->New->Project->ASP.NET Web Application and clicking OK.

After clicking the OK button, the following window would get displayed from where you need to select the Web API and click the OK button.


Step 2

We will now build the resource classes below to manage our GET, POST, PUT and DELETE services. Right-click the Templates folder in the Project Explorer window and select Add=>Class(see below).

Now it would make it easy for you to write actions to the API.

 
public IEnumerable GetStudents()  
{      
}  
					 
					 

Since we return a list of items, this action per convention will reply to.

// Get /API/students

So that's the convention embedded in the ASP.Net. Now, in this action, we will use our context to retrieve customers from the database.

 
namespace RestAPI.Controllers.API  
{  
public class StudentsController: ApiController  
{  
private readonly ApplicationDbContext _context;  
   
public StudentsController ()  
{  
_context = new ApplicationDbContext ();  
} 
// GET /API/students  
public IEnumerable GetStudents()  
{  
Return _context.Students.ToList();  
}  
}  
}  

                    

If the resource is not found, we return the not found HTTP reply otherwise we return the object.

 
// POST /api/students  
[HttpPost]  
public Customer CreateStudent(Student student)  
{  
}  					 
					 

This is the client argument that will be in the body of the request and will be automatically initialized by ASP.NET Web API Framework. Now, we should mark that action with HttpPost as we create the resource. And if we follow the naming convention, we don't even need to place the verb action upon action.

 
// POST /API/students  
public Student PostStudent(Student  student )  
{  
} 
					

Initially, however, this is not a good approach. Suppose you refactor the code in the future and rename your action then presumably your code will break. Therefore, you should always use the HTTP verbs at the top of the action.

Let's now insert the student object into the database with post request of api action.

 
// POST /api/students  
[HttpPost]  
public Student CreateStudent(Student student)  
{  
if (!ModelState.IsValid)  
{  
throw new HttpResponseException(HttpStatusCode.BadRequest);  
}  
_context.Students.Add(student);  
_context.SaveChanges();  
return student;  
}  					
					

Another measure: assume we want to update the student.

 
// PUT /api/students/1  
[HttpPut]  
public void UpdateStudent(int id, Student student)  
{  
if (!ModelState.IsValid)  
{  
throw new HttpResponseException(HttpStatusCode.BadRequest);  
}  
var studentmgr = _context.Studentd.SingleOrDefault(x => x.Id == id);  
if (studentmgr == null)  
{  
throw new HttpResponseException(HttpStatusCode.NotFound);  
}
studentmgr.Name = student.Name;  
studentmgr.Std = student.Std;  
_context.SaveChanges();  
}  					 
					 

Looking for Trusted .Net Development Company? Your Search ends here.

Here in this scenario, different people have different views about making the void or the object.

And if we do the removal action from APIs,

 
// Delete /API/students/1  
[HttpDelete]  
public void DeleteStudent(int id)  
{  
var stdmr = _context.Students.SingleOrDefault(x => x.ID == id);  
if (stdmr == null)  
{  
throw new HttpResponseException(HttpStatusCode.NotFound);  
}
_context.Students.Remove(stdmr);  
// Now the object is labeled as deleted in memory.  
// Now it is done  
_context.SaveChanges();  
}  				 
				 

Here's how we use the relaxing convention to construct the API.

Conclusion


Thus, the conclusion is always to follow the Restful agreement when working with Web Apis. Api web services are lighter than SOAP-based web services. They have multiple platforms. Restful HTTP verbs are very helpful in the application in inserting, deleting, updating, retrieving records. Here, we see how we use the factor and there are 2 different panels as query header and answer header. Most developers are confused about how to use Web API actions with jquery ajax. Here, we also consume our actions.

Building A Restful API in ASP.NET MVC 5 In ASP.NET MVC architecture, when the request comes to our application, MVC Framework drops this request to action in a controller, this action returns the view most of the time which is then analyzed by the razor view engine, and finally, the HTML markup is returned to the client. So, HTML tagging is generated on the server and then sent back to the client in this approach.   Table of Content 1.What is the benefit of this approach? 2.Restful Convention 3.Conclusion There is another way of generating the HTML tag, we can generate it on the client. This way, instead of sending back HTML tags, they can return raw data. What is the benefit of this approach? It requires fewer server resources (it potentially enhances the scalability of the application because each client will be responsible to generate its views). Raw data frequently needs less bandwidth than HTML markup. This allows data to potentially arrive more quickly to the customer. And this may improve the perceived efficiency of the app. This approach supports a wide range of customers like mobile applications and tablets. These applications are simply referred to as endpoints that get the data and generate the local view. We refer to these terminals as Data Services (Web APIs) because they only return data and not tags. Get a quote for top-notch API Integration Services! SEE HERE Web APIs are not only limited to cross-peripherals, they are also widely used in our web applications to add new functionality. Many popular sites such as Youtube, Facebook, and Twitter display public data services that we may consume in our web apps. We can merge their data into our app and provide new experiences for the new user. Those are the good things. Restful Convention So, you know what HTTP services and the web API are. Here, we are going to develop an application that supports a few various types of requests. GET /API/students (to get the list of students) GET /API/students/1 (to get the single student) POST /API/students (to add the student and add the students' data in Don't confuse GET and POST data requests, we use get request to get a list of resources or data. And we use post requests for creating the new one. Now, for updating the student, we use the PUT application. PUT /API/customers/1 This way the client id is in the URL and the data or properties to be updated will be in the body of the request. And lastly, remove the student. Delete /API/customers/1 We send the HttpDelete request to the endpoint. So what you see here, in terms of request types and parameters is a standard convention mentioned for requesting REST (Representational State Transfer) Read More: Overloading Action Method In Asp.net Mvc Step 1 First, create an ASP.NET Web application project in Visual Studio and call it RestAPI. You can do this by selecting File->New->Project->ASP.NET Web Application and clicking OK. After clicking the OK button, the following window would get displayed from where you need to select the Web API and click the OK button. Step 2 We will now build the resource classes below to manage our GET, POST, PUT and DELETE services. Right-click the Templates folder in the Project Explorer window and select Add=>Class(see below). Now it would make it easy for you to write actions to the API.   public IEnumerable GetStudents() { } Since we return a list of items, this action per convention will reply to. // Get /API/students So that's the convention embedded in the ASP.Net. Now, in this action, we will use our context to retrieve customers from the database.   namespace RestAPI.Controllers.API { public class StudentsController: ApiController { private readonly ApplicationDbContext _context; public StudentsController () { _context = new ApplicationDbContext (); } // GET /API/students public IEnumerable GetStudents() { Return _context.Students.ToList(); } } } If the resource is not found, we return the not found HTTP reply otherwise we return the object.   // POST /api/students [HttpPost] public Customer CreateStudent(Student student) { } This is the client argument that will be in the body of the request and will be automatically initialized by ASP.NET Web API Framework. Now, we should mark that action with HttpPost as we create the resource. And if we follow the naming convention, we don't even need to place the verb action upon action.   // POST /API/students public Student PostStudent(Student student ) { } Initially, however, this is not a good approach. Suppose you refactor the code in the future and rename your action then presumably your code will break. Therefore, you should always use the HTTP verbs at the top of the action. Let's now insert the student object into the database with post request of api action.   // POST /api/students [HttpPost] public Student CreateStudent(Student student) { if (!ModelState.IsValid) { throw new HttpResponseException(HttpStatusCode.BadRequest); } _context.Students.Add(student); _context.SaveChanges(); return student; } Another measure: assume we want to update the student.   // PUT /api/students/1 [HttpPut] public void UpdateStudent(int id, Student student) { if (!ModelState.IsValid) { throw new HttpResponseException(HttpStatusCode.BadRequest); } var studentmgr = _context.Studentd.SingleOrDefault(x => x.Id == id); if (studentmgr == null) { throw new HttpResponseException(HttpStatusCode.NotFound); } studentmgr.Name = student.Name; studentmgr.Std = student.Std; _context.SaveChanges(); } Looking for Trusted .Net Development Company? Your Search ends here. SEE HERE Here in this scenario, different people have different views about making the void or the object. And if we do the removal action from APIs,   // Delete /API/students/1 [HttpDelete] public void DeleteStudent(int id) { var stdmr = _context.Students.SingleOrDefault(x => x.ID == id); if (stdmr == null) { throw new HttpResponseException(HttpStatusCode.NotFound); } _context.Students.Remove(stdmr); // Now the object is labeled as deleted in memory. // Now it is done _context.SaveChanges(); } Here's how we use the relaxing convention to construct the API. Conclusion Thus, the conclusion is always to follow the Restful agreement when working with Web Apis. Api web services are lighter than SOAP-based web services. They have multiple platforms. Restful HTTP verbs are very helpful in the application in inserting, deleting, updating, retrieving records. Here, we see how we use the factor and there are 2 different panels as query header and answer header. Most developers are confused about how to use Web API actions with jquery ajax. Here, we also consume our actions.
Kapil Panchal

Kapil Panchal

A passionate Technical writer and an SEO freak working as a Content Development Manager at iFour Technolab, USA. With extensive experience in IT, Services, and Product sectors, I relish writing about technology and love sharing exceptional insights on various platforms. I believe in constant learning and am passionate about being better every day.

Build Your Agile Team

Enter your e-mail address Please enter valid e-mail

Categories

Ensure your sustainable growth with our team

Talk to our experts
Sustainable
Sustainable
 
Blog Our insights
Power Apps Solving 13 Legal Challenges
Power Apps Solving 13 Legal Challenges

There is a common misconception that bringing technology into the legal field won't be effective as this profession relies heavily on evidence and facts. However, if you look at it...

How to Automate Power BI Reports Using Power Automate
How to Automate Power BI Reports Using Power Automate

"Does Power Automate work with Power BI?”. If you think the same, you’re at the right place. Manual reporting plays an important role in business decision-making but requires more...

What’s New in .NET 9?
What’s New in .NET 9?

Today, we’re thrilled to present you with the first glimpse of .NET 9 release and let you know what features and updates you can anticipate in this new version. Various professionals believe that it’s the right time to explore and adopt the latest version of .NET for your upcoming projects. It is even recommended for projects built using .NET 6 or .NET 8, due to the framework updates made in this version.