skip to Main Content
[HttpPost]
[Route("[action]")]
public string GetString()
{
    return "abc";
}

When I use the method above in an asp.net core controller the result is not formatted as json and the content type is text/plain. While every non-primitive result type is indeed formatted as json. How can I achive the same for string as return type?

3

Answers


  1. You can wrap it in an Ok ActionResult.

    [HttpPost]
    [Route("[action]")]
    public ActionResult<string> GetString()
    {
        return Ok("abc");
    }
    

    (It might work without the Ok as we also changed the return type to ActionResult<string>)

    Login or Signup to reply.
  2. Your return value is not a valid json, but you can do the following to change the content type only

    public class TestController : ControllerBase
    {
        [HttpPost]
        [Route("[action]")]
        public IActionResult GetString()
        {
            return new JsonResult("abc");
        }
    }
    

    Or you can inherit from Controller instead of ControllerBase

    public class TestController : Controller
    {
        [HttpPost]
        [Route("[action]")]
        public IActionResult GetString()
        {
            return Json("abc");
        }
    }
    
    Login or Signup to reply.
  3. your "abc" is not valid json string and it doesnt make any sense to return an invalid json string as a json content.

    but if you want to return as an action output a valid json string, for example

    var jsonString = "["abc"]";
    
    //or
    var jsonString = "{"name":"abc"}";
    

    you can use this syntax

    return Content(jsonString, "application/json");
    

    or if you use a minimal API

     return Results.Content(jsonString, "application/json");
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search