Neo
Neo

Reputation: 16219

How do I format response data into ASP.NET CORE?

I have existing ASP.Net WEB API with below output response format , I'm converting that project into ASP.NET CORE.

I have already gone through this link

public class MyClass
{       
    [JsonProperty("id")]
    public long Id { get; set; }

    [JsonProperty("name")]
    public string Name { get; set; }       
}

// Helper.cs
public class ApiResponse
{
    [DataMember(EmitDefaultValue = false)]
    [JsonProperty(PropertyName = "data")]
    public object Data { get; set; }

    public ApiResponse(HttpStatusCode statusCode, object result = null)
    {
        Data = result;
    }
}

// Helper.cs
public class WrappingHandler<T> where T : class
{
    public static HttpResponseMessage ResponseHandler(IEnumerable<T> responseObject, HttpRequestMessage request)
    {
        HttpResponseMessage response = request.CreateResponse(HttpStatusCode.OK, responseObject);
        var newResponse = request.CreateResponse(HttpStatusCode.OK, new ApiResponse(HttpStatusCode.OK, responseObject));
        return newResponse;
    }
}

// HomeController.cs

public HttpResponseMessage RetriveData(string name)
{
    try
    {
        var mydata = _context.Get(name);
        return WrappingHandler<MyClass>.ResponseHandler(mydata, Request);
    }
}

// output for asp.net webapi 
{
    "data": [
        {
            "id": 32,
            "name": "Hi everyone" 
        }
    ]
}

Now I'm converting the project to ASP.NET CORE so I need to change the return type as well from HttpResponseMessage to IActionResult orJsonResult` but how do I manage my custom output format changes?

I mean what changes I need to do into WrappingHandler and ApiResponse anyhelp?

Upvotes: 0

Views: 3142

Answers (1)

Set
Set

Reputation: 49779

You are mixing different things.

Regarding result that controller action should return (from doc):

An action isn't required to return any particular type; MVC supports any object return value. If an action returns an IActionResult implementation and the controller inherits from Controller, developers have many helper methods corresponding to many of the choices. Results from actions that return objects that are not IActionResult types will be serialized using the appropriate IOutputFormatter implementation.

IActionResult is just an interface that defines following contract:

Task ExecuteResultAsync(ActionContext context)

And yes, ASP.NET Core provides a lot of predefined classes for different purpose:

  • simple StatusCodeResult or more specific classes like OkResult, NotFoundResult, etc
  • for particular format: JsonResult, ContentResult, etc..

So you are free to select what is more suitable for your case.


Regarding the WrappingHandler replacement -it is the controller action main responsibility to create a response. Others better should work with data model only. In other words, your WrappingHandler class should be some kind of service with only something like this:

public class DataService
{ 
   public MyClass RetriveData(string name)
   {
      var mydata = _context.Get(name);
      return mydata
   }
 }
  • If you want to format the final response, like adding custom headers, consider using the MVC Filters, in particular - ResultFilter.
  • If you need some generic response validation - use ActionFilter, d ExceptionFilter or ExceptionHandler middleware. In other words, if above RetriveData method may raise exceptions and you do not want to have 200 OK as a response in this case - this is not the DataService class responsibility to handle this logic.

Upvotes: 1

Related Questions