0

0

I'm building an ASMX webservice on .NET 4.5 and due to the way it's structured, it's hard to add something like HttpContext.Current.Response.Status to my API response, instead I'd prefer to return something like this

{'status': 'success', 'error_message': '', 'data': [{object1}, {object2},{etc}]} or {'status': 'fail', 'error_message': 'Error Occured', 'data' = []}

I see this format a lot but I've never seen a way to create it in C#, other than hardcoding it or creating multiple classes. How can I achieve a format like this in .NET?

Axel Neo
  • 11
  • 1
  • 2
  • What do you mean by hard-coding in this context? What have you tried so far, to add to the response? – ryanwebjackson Nov 03 '21 at 23:24
  • Use an anonymous type if you want to neither hardcore nor create classes – Caius Jard Nov 04 '21 at 00:31
  • 1
    @ryanwebjackson I see my colleagues often using something like 'HttpContext.Current.Response.Write("{\"status\": true, \"data\": [{" + somefunction() + "}]}")', in their defense, they mostly use this when their function has some basic select query from the DB. @ CaiusJard Thanks for the suggestion, I'll look into anonymous types. – Axel Neo Nov 04 '21 at 04:12
  • Yikes. That at least adds clarity to what you mean, but I wouldn't recommend it. – ryanwebjackson Nov 05 '21 at 20:48
  • Does this help? https://stackoverflow.com/questions/288850/how-to-return-json-from-a-2-0-asmx-web-service – ryanwebjackson Nov 05 '21 at 20:50
  • It's been so long since I've done an asmx service, but would recommend something like Tom's answer - wait until the last minute to serialize. Depending on your application, you may want to write a wrapper so you can swap out the JSON library, or modify serialization. – ryanwebjackson Nov 05 '21 at 20:57

0 Answers0