0

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?

always-a-learner
  • 3,671
  • 10
  • 41
  • 81
Neo
  • 15,491
  • 59
  • 215
  • 405
  • 1
    Why do you need `WrappingHandler`? Why not return the response directly from the action? – peco Sep 04 '17 at 11:15
  • `WrappingHandler` i'm doing some formating like I want result into `data` and also adding few more extra fields like `metadata` into output. thats why using WrappingHandler and doing formatting. it works perfect into asp.net webapi but how to use/make these chnages into asp.net core return response – Neo Sep 04 '17 at 11:36

1 Answers1

1

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.
Set
  • 47,577
  • 22
  • 132
  • 150
  • good one got you but what about response format like add key for output response ` "data": [` or add more fields like `data` in output json? – Neo Sep 04 '17 at 12:45
  • 1
    @Neo Consider this as part of data Model (MyClass) or response Model (ApiResponse) modification. My main points are that logic like `new ApiResponse(HttpStatusCode.OK, )` should be in controller action. And then using filters you may modify/replace `ApiResponse` instance if needed. – Set Sep 04 '17 at 13:26