简体   繁体   中英

Returning JSON results to API calls from already existing Controller actions in ASP.NET MVC 5

I am new to ASP.NET WebApi. I am working on an ASP.NET MVC 5 project.

When I started it, it wasn't built considering WebApi functionality. I kept on building on it. It's completely an MVC project as of now. I have coded lots of Controllers, which contain various actions, like fetching results of queries from DB.

Now I want to add WebApi support to the project. For eg: I have a controller action, which fetches a bunch of data from the DB. Now, I need to return the data in say, JSON format.

My question is, do I need to write all such functions once again to fetch the data and return it as JSON? I do have a lot of actions across various controllers. Rewriting those actions once again would be a lot of work. If possible, how can it be done with minimal addition to the code, while also not disrupting the normal functioning of the current MVC project?

This is just an example of an action in one of the MVC controllers:

public string GetName()
{
    string constr = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
    string stud_name;

    using (SqlConnection con = new SqlConnection(constr))
    {
        SqlCommand cmd = new SqlCommand('SELECT name FROM Table WHERE id = 232', con);

        stud_name = Convert.ToString(cmd.ExecuteScalar());

    }

    return stud_name;

}

I had written this function some time ago. There are several others like this, which return other things. Considering this action, how do I return the string as JSON object to the api call? Is there a way to do that without rewriting the function for ApiController?

You can add methods to the common class and call these methods from both types of controller's action methods.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM