Computer >> Máy Tính >  >> Lập trình >> C#

Làm cách nào để trả về kiểu kết quả tùy chỉnh từ một phương thức hành động trong C # ASP.NET WebAPI?

Chúng tôi có thể tạo lớp tùy chỉnh của riêng mình dưới dạng loại kết quả bằng cách triển khai giao diện IHttpActionResult . IHttpActionResult chứa một phương thức duy nhất, ExecuteAsync, tạo không đồng bộ một cá thể HttpResponseMessage.

public interface IHttpActionResult
{
   Task<HttpResponseMessage> ExecuteAsync(CancellationToken
   cancellationToken);
}

Nếu một hành động của bộ điều khiển trả về một IHttpActionResult, Web API sẽ gọi ExecuteAsyncmethod để tạo một HttpResponseMessage. Sau đó, nó chuyển đổi HttpResponseMessage thành một thông báo phản hồi HTTP.

Ví dụ

Để có kết quả tùy chỉnh của riêng mình, chúng ta phải tạo một lớp có giao diện implementIHttpActionResult.

using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using System.Web.Http;
namespace DemoWebApplication.Controllers{
   public class CustomResult : IHttpActionResult{
      string _value;
      HttpRequestMessage _request;
      public CustomResult(string value, HttpRequestMessage request){
         _value = value;
         _request = request;
      }
      public Task<HttpResponseMessage> ExecuteAsync(CancellationToken
      cancellationToken){
         var response = new HttpResponseMessage(){
            Content = new StringContent($"Customized Result: {_value}"),
            RequestMessage = _request
         };
         return Task.FromResult(response);
      }
   }
}

Hành động Contoller -

Ví dụ

using DemoWebApplication.Models;
using System.Collections.Generic;
using System.Linq;
using System.Web.Http;
namespace DemoWebApplication.Controllers{
   public class DemoController : ApiController{
      public IHttpActionResult Get(int id){
         List<Student> students = new List<Student>{
            new Student{
               Id = 1,
               Name = "Mark"
            },
            new Student{
               Id = 2,
               Name = "John"
            }
         };
         var studentForId = students.FirstOrDefault(x => x.Id == id);
         return new CustomResult(studentForId.Name, Request);
      }
   }
}

Đây là đầu ra của người đưa thư của điểm cuối trả về kết quả tùy chỉnh.

Làm cách nào để trả về kiểu kết quả tùy chỉnh từ một phương thức hành động trong C # ASP.NET WebAPI?