Web API একশন মেথডের নিচের রিটার্ন টাইপগুলো থাকতে পারে:
- Void
- Primitive Type / Complex Type
- HttpResponseMessage
- IHttpActionResult
১. Void
সকল একশন মেথড কিছু রিটার্ন করবে সেটি বাধ্যতামূলক নয়। এটি void রিটার্ন টাইপ থাকতে পারে।
উদাহরণ
using DemoWebApplication.Models;
using System.Web.Http;
namespace DemoWebApplication.Controllers
{
public class DemoController : ApiController
{
public void Get([FromBody] Student student)
{
// Some Operation
}
}
}

Void রিটার্ন টাইপের একশন মেথড 204 No Content রেসপন্স রিটার্ন করে।
২. Primitive Type / Complex Type
একশন মেথড primitive type (int, string) বা complex type (List ইত্যাদি) রিটার্ন করতে পারে।
উদাহরণ
using DemoWebApplication.Models;
using System.Collections.Generic;
using System.Web.Http;
namespace DemoWebApplication.Controllers
{
public class DemoController : ApiController
{
public List Get([FromBody] Student student)
{
return new List
{
$"The Id of the Student is {student.Id}",
$"The Name of the Student is {student.Name}"
};
}
}
}

৩. HttpResponseMessage
`HttpResponseMessage` তখন ব্যবহৃত হয় যখন আমরা একশন মেথডের রিটার্ন টাইপ (একশন রেজাল্ট) কাস্টোমাইজ করতে চাই। রেসপন্সগুলো স্ট্যাটাস কোড, কন্টেন্ট টাইপ, এবং রিটার্ন করা ডেটা দিয়ে `HttpResponseMessage`-এ প্রদান করে কাস্টোমাইজ করা হয়।
উদাহরণ
using DemoWebApplication.Models;
using System.Net;
using System.Net.Http;
using System.Web.Http;
namespace DemoWebApplication.Controllers
{
public class DemoController : ApiController
{
public HttpResponseMessage Get([FromBody] Student student)
{
if (student.Id > 0)
{
return Request.CreateResponse(HttpStatusCode.OK, $"The Student Id is {student.Id} and Name is {student.Name}");
}
else
{
return Request.CreateResponse(HttpStatusCode.BadRequest, "InValid Student Id");
}
}
}
}

উপরের উদাহরণে আমরা দেখতে পাচ্ছি যে রেসপন্স কাস্টোমাইজড। যেহেতু একশন মেথডে পাস করা Id 0, তাই else ব্লক এক্সিকিউট হয়েছে এবং এরর মেসেজসহ 400 Bad Request রিটার্ন হয়েছে।
৪. IHttpActionResult
`IHttpActionResult` ইন্টারফেস Web API 2-এ ইন্ট্রোডিউস করা হয়েছিল। মূলত এটি একটি `HttpResponseMessage` ফ্যাক্টরি ডিফাইন করে। `IHttpActionResult` `System.Web.Http` নেমস্পেসে আছে। `HttpResponseMessage`-এর চেয়ে `IHttpActionResult` ব্যবহার করার সুবিধাগুলো নিচে দেওয়া হলো:
- কন্ট্রোলার ইউনিট টেস্টিং সহজ করে।
- HTTP রেসপন্স তৈরির কমন লজিক আলাদা ক্লাসে সরিয়ে দেয়।
- কন্ট্রোলার একশনের ইন্টেন্ট পরিষ্কার করে, লো-লেভেল রেসপন্স কন্সট্রাকশনের ডিটেইল হাইড করে।
উদাহরণ
using DemoWebApplication.Models;
using System.Collections.Generic;
using System.Web.Http;
namespace DemoWebApplication.Controllers
{
public class DemoController : ApiController
{
public IHttpActionResult Get([FromBody] Student student)
{
var result = new List
{
$"The Id of the Student is {student.Id}",
$"The Name of the Student is {student.Name}"
};
return Ok(result);
}
}
}
