Web API एक्शन मेथड के निम्नलिखित रिटर्न टाइप्स हो सकते हैं।
- Void
- Primitive Type/Complex Type
- HttpResponseMessage
- IHttpActionResult
1. Void
यह आवश्यक नहीं है कि सभी एक्शन मेथड्स कुछ न कुछ लौटाएं। इनका रिटर्न टाइप void हो सकता है।
उदाहरण
using DemoWebApplication.Models;
using System.Web.Http;
namespace DemoWebApplication.Controllers
{
public class DemoController : ApiController
{
public void Get([FromBody] Student student)
{
// कुछ ऑपरेशन
}
}
}

Void रिटर्न टाइप वाला एक्शन मेथड 204 No Content रिस्पॉन्स लौटाएगा।
2. Primitive Type/Complex Type
एक्शन मेथड int, string जैसे प्रिमिटिव टाइप या 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}"
};
}
}
}

3. 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 लौटाया जाता है।
4. 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);
}
}
}
