简体   繁体   中英

Setting the file name returned by ASP .NET Web API

I am looking to set the name of the file that is being returned by the ASP .NET WEB API. Currently its just returns in the name of the parameters that is being passed in the URL. But what if I need then to be returned as ABC.JSON

public class NewTestController : ApiController
{
public string Getdetails([FromUri] string[] id)
{using (OracleConnection dbconn = new OracleConnection("DATA SOURCE=J;PASSWORD=C;PERSIST SECURITY INFO=True;USER ID=T"))
    {
        var inconditions = id.Distinct().ToArray();
        var srtcon = string.Join(",", inconditions);
        DataSet userDataset = new DataSet();
        var strQuery = @"SELECT 
                       * from STPR_STUDY where STPR_STUDY.STD_REF IN (" + srtcon + ")";
        OracleCommand selectCommand = new OracleCommand(strQuery, dbconn);
        OracleDataAdapter adapter = new OracleDataAdapter(selectCommand);
        DataTable selectResults = new DataTable();
        adapter.Fill(selectResults);
        return JsonConvert.SerializeObject(selectResults);
}}}

I did see in other forums using Content-Disposition but I am not using HTTPResponse in code. How can this be done. Thanks

I tried like below

 OracleCommand selectCommand = new OracleCommand(strQuery, dbconn);
            OracleDataAdapter adapter = new     OracleDataAdapter(selectCommand);
            DataTable selectResults = new DataTable();
            adapter.Fill(selectResults);
            string result =  JsonConvert.SerializeObject(selectResults);
            HttpResponseMessage response = new HttpResponseMessage();
            response.StatusCode = HttpStatusCode.OK;
            response.Content = new StreamContent(result);
            response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
            {
                FileName = "Abc.JSON"
            };
     return(result);

But it throws the error in StreamContent saying,the best overloaded method match for has some invalid arguments in StreamConent

You can use CreateResponse method of Request object like below

    public HttpResponseMessage Get()
    {
        string fileName = "abc.json";
        return Request.CreateResponse(HttpStatusCode.OK, fileName);
    }

Edit 1:

   string contentDisposition = "inline; filename=abc.json";
   HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.OK, byteInfo, MediaTypeHeaderValue.Parse("application/json"));
   response.Content.Headers.ContentDisposition = ContentDispositionHeaderValue.Parse(contentDisposition);
   return response;

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