XamDev
XamDev

Reputation: 3647

Download file or send json in web api method

I have written web api in which it is returning/producing json response. Below is the code for the same.

[HttpGet]
[Route("someapi/myclassdata")]
[Produces("application/json")]
public MyClassData GetMyClassData(int ID, int isdownload)
{
   myclassdata = myclassdataBL.GetMyClassData(ID);
   return myclassdata;

    //**Commented Code**
   //if(isdownload==1)
   //{
        //download file
   //}
   //else
   //{
        // send response
   //}
}

Till now it is working fine. Now I want to create and download the file based on value in 'isDownload' parameter.

So after getting the data if files needs to be downloaded I want to download the file otherwise I will send the json response.

So, my question is can we send json reponse or download the file in same web api method.

Any help on this appreciated!

Upvotes: 0

Views: 2288

Answers (1)

Kirk Larkin
Kirk Larkin

Reputation: 93003

Yes, this is easily achievable. Rather than returning MyClassData explicitly like that, you can return an IActionResult, like this:

public IActionResult GetMyClassData(int ID, int isdownload)
{
   myclassdata = myclassdataBL.GetMyClassData(ID);

   if (isDownload == 1)
       return File(...);

   return Ok(myclassdata);
}

Both File(...) and Ok(...) return an IActionResult, which allows for the dynamism you're asking for here.

Note: You can also just return Json(myclassdata) if you want to force JSON, but by default this will be JSON anyway and is more flexible with e.g. content-negotiation.

See Controller action return types in ASP.NET Core Web API for more details.

Upvotes: 1

Related Questions