Csharp How to Read Web Api Response Within Response
Action Method Return Blazon
In the previous department, you learned about parameter binding with Spider web API action method. Here, yous will learn about the return types of activeness methods which in plow volition be embedded in the Spider web API response sent to the client.
The Web API action method can have following return types.
- Void
- Primitive type or Complex blazon
- HttpResponseMessage
- IHttpActionResult
Void
It's non necessary that all action methods must return something. Information technology tin take void render type.
For example, consider the following Delete action method that merely deletes the student from the data source and returns goose egg.
public grade StudentController : ApiController { public void Delete(int id) { DeleteStudentFromDB(id); } }
Every bit you can come across in a higher place Delete activity method returns void. It volition send 204 "No Content" status code as a response when you send HTTP DELETE request as shown below.
Primitive or Complex Type
An action method can return primitive or other custom complex types as other normal methods.
Consider the following Get action methods.
public class Student { public int Id { get; set; } public string Proper name { go; set; } } public class StudentController : ApiController { public int GetId(string name) { int id = GetStudentId(name); return id; } public Pupil GetStudent(int id) { var student = GetStudentFromDB(id); return pupil; } }
Every bit you can see above, GetId action method returns an integer and GetStudent activity method returns a Student blazon.
An HTTP GET request http://localhost:xxxx/api/student?name=john
will return post-obit response in Fiddler.
An HTTP GET request http://localhost:xxxx/api/student?id=ane
volition return post-obit response in Fiddler.
HttpResponseMessage
Web API controller always returns an object of HttpResponseMessage to the hosting infrastructure. The following figure illustrates the overall Web API asking/response pipeline.
Visit Web API HTTP Message Life Cycle Poster for more details.
Every bit y'all can see in the above effigy, the Web API controller returns HttpResponseMessage object. You lot can too create and return an object of HttpResponseMessage directly from an action method.
The advantage of sending HttpResponseMessage from an action method is that y'all tin configure a response your way. You can prepare the condition code, content or fault bulletin (if any) as per your requirement.
public HttpResponseMessage Get(int id) { Student stud = GetStudentFromDB(id); if (stud == null) { return Asking.CreateResponse(HttpStatusCode.NotFound, id); } render Request.CreateResponse(HttpStatusCode.OK, stud); }
In the above activeness method, if there is no educatee with specified id in the DB then it will render HTTP 404 Not Plant status code, otherwise it will return 200 OK status with student data.
For example, an http Become request http://localhost:xxxx/api/student?id=100
will go following response because pupil with id=100 does not exists in the DB.
The aforementioned mode, an HTTP Become request http://localhost:60464/api/pupil?id=1
will get following response considering student with id=1 exists in the database .
IHttpActionResult
The IHttpActionResult was introduced in Spider web API 2 (.NET four.five). An activeness method in Web API two can return an implementation of IHttpActionResult form which is more or less similar to ActionResult course in ASP.NET MVC.
You lot can create your own class that implements IHttpActionResult or use various methods of ApiController
grade that returns an object that implement the IHttpActionResult.
public IHttpActionResult Get(int id) { Student stud = GetStudentFromDB(id); if (stud == zilch) { return NotFound(); } return Ok(stud); }
In the to a higher place case, if student with specified id does not exists in the database so information technology will render response with the status code 404 otherwise it sends student data with status code 200 as a response. Equally you can see, we don't have to write much code because NotFound() and Ok() method does information technology all for us.
The following table lists all the methods of ApiController class that returns an object of a class that implements IHttpActionResult interface.
ApiController Method | Description |
---|---|
BadRequest() | Creates a BadRequestResult object with status lawmaking 400. |
Conflict() | Creates a ConflictResult object with condition code 409. |
Content() | Creates a NegotiatedContentResult with the specified status code and information. |
Created() | Creates a CreatedNegotiatedContentResult with status code 201 Created. |
CreatedAtRoute() | Creates a CreatedAtRouteNegotiatedContentResult with condition code 201 created. |
InternalServerError() | Creates an InternalServerErrorResult with status code 500 Internal server error. |
NotFound() | Creates a NotFoundResult with status code404. |
Ok() | Creates an OkResult with condition code 200. |
Redirect() | Creates a RedirectResult with condition lawmaking 302. |
RedirectToRoute() | Creates a RedirectToRouteResult with status code 302. |
ResponseMessage() | Creates a ResponseMessageResult with the specified HttpResponseMessage. |
StatusCode() | Creates a StatusCodeResult with the specified http status code. |
Unauthorized() | Creates an UnauthorizedResult with status code 401. |
Visit MSDN to know all the members of ApiController.
Create Custom Result Type
You lot can create your own custom class as a result type that implements IHttpActionResult interface.
The following example demonstrates implementing IHttpActionResult form.
public form TextResult : IHttpActionResult { string _value; HttpRequestMessage _request; public TextResult(string value, HttpRequestMessage request) { _value = value; _request = request; } public Job<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken) { var response = new HttpResponseMessage() { Content = new StringContent(_value), RequestMessage = _request }; return Chore.FromResult(response); } }
Now, you can return TextResult object from the activeness method as shown below.
public IHttpActionResult GetName(int id) { string name = GetStudentName(id); if (Cord.IsNullOrEmpty(name)) { render NotFound(); } render new TextResult(proper noun, Request); }
Source: https://www.tutorialsteacher.com/webapi/action-method-return-type-in-web-api
0 Response to "Csharp How to Read Web Api Response Within Response"
Post a Comment