代码之家  ›  专栏  ›  技术社区  ›  XamDev

用webapi方法下载文件或发送json

  •  0
  • XamDev  · 技术社区  · 6 年前

    [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
       //}
    }
    

    到目前为止,它运行良好。现在,我想根据

    所以,我的问题是,我们可以发送json响应或下载相同的webapi方法的文件。

    1 回复  |  直到 6 年前
        1
  •  1
  •   Kirk Larkin    6 年前

    是的,这是很容易实现的。而不是回来 MyClassData 显式地,你可以返回一个 IActionResult ,如下所示:

    public IActionResult GetMyClassData(int ID, int isdownload)
    {
       myclassdata = myclassdataBL.GetMyClassData(ID);
    
       if (isDownload == 1)
           return File(...);
    
       return Ok(myclassdata);
    }
    

    两者 File(...) Ok(...) 返回 IActionResult公司

    注意:你也可以 return Json(myclassdata) 如果您想强制使用JSON,但默认情况下,这将是JSON,并且在内容协商等方面更加灵活。

    Controller action return types in ASP.NET Core Web API 更多细节。