ASP.NET core webapi return data type _ platform: Windows (4)

It is common to find that most of the time the front-end requests the interface and returns JSON. So let’s see how the API is written later.

First we use the default created controller (ValuesController) as our reference:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;

namespace mynetcorewebapi.Controllers
{
    [RouteAttribute("api/[controller]")]
    [ApiController]
    public class ValuesController : ControllerBase
    {
        // GET api/values
        [HttpGet]
        public ActionResult<IEnumerable<string>> Get()
        {
            return new string[] { "value1", "value2" };
        }

        // GET api/values/5
        [HttpGet("{id}")]
        public ActionResult<string> Get(int id)
        {
            return "value";
        }

        // POST api/values
        [HttpPost]
        public void Post([FromBody] string value)
        {
        }

        // PUT api/values/5
        [HttpPut("{id}")]
        public void Put(int id, [FromBody] string value)
        {
        }

        // DELETE api/values/5
        [HttpDelete("{id}")]
        public void Delete(int id)
        {
        }
    }
}
Copy the code

We noticed that the ActionResult<IEnumerable> return value in the code above is a collection of string generics

So if we don’t want to restrict the type every time we write ActionResult

If you want to keep writing a little bit less code, you can write object directly, so this is what the simplification looks like

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;

namespace mynetcorewebapi.Controllers{[ApiController]
    public class ValuesController : ControllerBase{[RouteAttribute("api/values/get")]
        [HttpGet]
        public ActionResult<object> Get()
        {
            return new string[] { "value1"."value2"}; }}}Copy the code

And this:

using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; namespace mynetcorewebapi.Controllers { [ApiController] public class ValuesController : ControllerBase { [RouteAttribute("api/values/get")] [HttpGet] public object Get() { return new string[] { "value1", "value2" }; }}}Copy the code

Results after the interview (both) :

Welcome to qq group communication: 704028989