Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Returning Json from an MVC controller that extends Apicontroller

I'm trying to return a Json string from an MVC controller in a WebAPI application, but am unable to use return Json(... because the class being used extends ApiController and not Controller (I believe).

Is there an alternative method to do what I'm trying to do (e.g. return a different type)? Or a workaround?

This is my controller code:

public class SocialController : ApiController 
{
    public ActionResult Get(SocialRequest request) // or JsonResult?
    {
        JavaScriptSerializer js = new JavaScriptSerializer();
        string jsontest = js.Serialize(request); // just serializing back and forth for testing

        return Json(jsontest, JsonRequestBehavior.AllowGet);
    }
}

The error I'm receiving is "System.Web.Helpers.Json is a type but is used like a variable."

I've found the following related SO question but it hasn't solved it for me, if anyone can elaborate I'd really appreciate it (and dish out the rep points): Why Json() Function is unknown

like image 535
WheretheresaWill Avatar asked Apr 04 '13 08:04

WheretheresaWill


People also ask

How do I return JSON in Web API net core?

To return data in a specific format from a controller that inherits from the Controller base class, use the built-in helper method Json to return JSON and Content for plain text. Your action method should return either the specific result type (for instance, JsonResult ) or IActionResult .

How do I return JSON data to view?

The Controller Action method will be called using jQuery POST function and JSON data will be returned back to the View using JsonResult class object. Note: For beginners in ASP.Net MVC, please refer my article ASP.Net MVC Hello World Tutorial with Sample Program example.

What is JSON in MVC with example?

"JSON" (JavaScript Object Notation) is a lightweight text-based open standard designed for human-readable data interchange. When working together with "jQuery" and "ASP.NET MVC" in building web applications, it provides an efficient mechanism to exchange data between the web browser and the web server.

What is JsonRequestBehavior AllowGet?

If you need to send JSON in response to a GET, you'll need to explicitly allow the behavior by using JsonRequestBehavior. AllowGet as the second parameter to the Json method. However, there is a chance a malicious user can gain access to the JSON payload through a process known as JSON Hijacking.


1 Answers

In Asp.net Web Api you don't have ActionResults anymore. You simply return the object you need. The framework converts the object to the proper response (json, xml or other types)

[HttpGet]
public IEnumerable<string> GetUsers(SocialRequest request)
{
    return _applicationsService.GetUserss(request);
}
like image 64
Catalin Avatar answered Oct 05 '22 17:10

Catalin