How to Send API Responses in ASP.NET Web API & MVC
Hi there, I am a software programmer with lots of interests in learning new age technologies. I enjoy writing clean and crisp code.
Hi there, welcome to another blog! If you’re working with .NET, you’ve probably built APIs in either ASP.NET Web API or ASP.NET MVC. But here’s the deal 👉 writing controllers is easy, sending clean and consistent responses is where many developers trip up.
So today, let’s learn how to send perfect API responses in both frameworks — without turning it into rocket science 🚀
What is an API Response Anyway?
Think of an API response like ordering food 🍔:
Success response → You get your burger, fries, and a smile.
Error response → They tell you, "Sorry, burger sold out!"
Your API should behave the same way 👇
✅ Success Example:
{ "status": "success", "message": "User fetched successfully", "data": { "id": 101, "name": "Hetal" } }
❌ Error Example:
{ "status": "error", "message": "User not found", "code": 404 }
🎯 ASP.NET Web API (Modern Style)
ASP.NET Web API was built exactly for APIs, so it has built-in helpers.
Example:
public class UsersController : ApiController { [HttpGet] [Route("api/users/{id}")] public IHttpActionResult GetUser(int id) { if (id == 101) { return Ok(new { status = "success", message = "User fetched successfully", data = new { id = 101, name = "Hetal" } }); }
return Content(HttpStatusCode.NotFound, new { status = "error", message = "User not found", code = 404 }); } }
👉 Notice how we used:
Ok() for 200 success
Content(HttpStatusCode.NotFound, …) for 404 errors
Super clean ✅
🎯 ASP.NET MVC (Before Web API Days)
Now, MVC wasn’t built for APIs — it was built for returning Views. But you can still return JSON responses using JsonResult.
Example:
public class UsersController : Controller { [HttpGet] public JsonResult GetUser(int id) { if (id == 101) { return Json(new { status = "success", message = "User fetched successfully", data = new { id = 101, name = "Hetal" } }, JsonRequestBehavior.AllowGet); }
return Json(new { status = "error", message = "User not found", code = 404 }, JsonRequestBehavior.AllowGet); } }
👉 Here we used Json() instead of Ok(). 👉 You must allow JsonRequestBehavior.AllowGet for GET requests (MVC security feature).
⚡ Best Practices (Works for Both Web API & MVC)
✔ Always send status + message + data ✔ Use HTTP status codes properly (200, 201, 400, 404, 500) ✔ Keep the response consistent (don’t change formats randomly) ✔ Don’t leak sensitive info like passwords 🔑
🎉 Conclusion
In Web API, use Ok(), BadRequest(), NotFound() → much cleaner.
In MVC, use JsonResult since MVC wasn’t originally designed for APIs.
Either way, your goal is the same: make responses clear, consistent, and developer-friendly ✨.


