2016-07-25 55 views
0

我正在設置由ASP .NET WEB API返回的文件的名稱。目前,它只是以URL中傳遞參數的名義返回。但要返回,如果我需要什麼,然後作爲ABC.JSON設置由ASP .NET Web API返回的文件名

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); 
}}} 

我沒有看到在使用內容處置其他論壇,但我不是在代碼中使用類HTTPResponse。如何才能做到這一點。由於

我試着像下面

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); 

但它引發的錯誤StreamContent說,最好的重載的方法匹配具有StreamConent一些無效參數

+1

從控制器返回'string'。您應該至少使用'IHttpActionResult',但更好的'HttpResponseMessage'來設置您的文件名 –

+0

Teo van kot,我嘗試使用HTTPResponseMessage和我在最佳重載方法匹配中獲取錯誤在StreamConent中有一些無效參數。我正在創建我的第一個Web API – trx

+0

從API返回序列化的DataTable沒有意義,您希望在客戶端獲得的最終結果是什麼? – Win

回答

1

您可以使用Request對象的CreateResponse方法一樣下面

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

編輯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; 
+0

從DataTable轉換爲JSON但我將DataTable轉換爲JSON。所以我不會在String中返回它們。我很抱歉,我是新的,有點卡住了。 – trx

+0

即使它是字符串,也應該使用HttpResponseMessage將數據返回給客戶端。如果你需要幫助,如何在客戶端使用它,讓我知道 – Paresh

+0

'DataTable selectResults = new DataTable(); adapter.Fill(selectResults); string result = JsonConvert.SerializeObject(selectResults); HttpResponseMessage response = new HttpResponseMessage(); response.StatusCode = HttpStatusCode.OK; var fileName =「abc.json」; return Request.CreateResponse(HttpStatusCode.OK,fileName);'我試過這段代碼,它將NewTest.JSOn作爲ABC.JSON中的數據進行操作。它不列入返回原始數據 – trx