trx
trx

Reputation: 2157

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

Upvotes: 0

Views: 2004

Answers (1)

Paresh
Paresh

Reputation: 993

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;

Upvotes: 1

Related Questions