2016-07-04 6 views
0

URLを介してナビゲートできるシンプルなWeb APIコントローラがあり、.csvファイルがダウンロードされます。今、私はいくつかのjQueryを書こうとしていますが、ボタンをクリックするとダウンロードできますが、何か不足しています。Web APIコントローラはcsvをダウンロードしますが、jQueryでは機​​能しません。

public HttpStatusCode Get(string id) 
{ 
    var reportString = AskWebBusiness.Reports.GenerationQuestionReport(id); 
    var response = HttpContext.Current.Response; 
    response.ContentType = "text/csv"; 
    response.AppendHeader("Content-Disposition", "attachment;filename=" + "Questions Report.csv"); 
    response.Write(reportString); 
    return HttpStatusCode.OK; 
} 

このコードは間違いなく動作し、ダウンロードを促すためにURLにアクセスできます。

$('.js-btn-download-content').click(function (event) { 
     var currentLanguage = getCulture(); 
     var url = baseUrl + 'report/get/' + currentLanguage; 
     event.preventDefault(); 
     $('.loadingContent-download').fadeIn(200); 
     $.ajax({ 
      headers: { 
       Accept : "text/csv; charset=utf-8", 
       "Content-Type": "text/csv; charset=utf-8" 
      }, 
      url: url, 
      dataType: "text/csv", 
      success: function (data) { 
       $('.loadingContent-download').fadeOut(200); 
       // Not sure about code below 
       //var xmlDoc = $.parseXML(data); 
       //var $xml = $(xmlDoc); 
       //var $title = $xml.find("200"); 
       //if ($title) { 
        //$('.contentDownloaded-download p').html('Content donwloaded!'); 
        //$('.contentDownloaded-download').show(); 
       //} else { 
        //$('.contentDownloaded-download p').html('Download failed! Please try again.'); 
        //$('.contentDownloaded-download').show(); 
       // 
      } 
     }); 
     $('.js-btn-confirm').click(function() { 
      $('.contentDownloaded-download').fadeOut(200); 
     }); 
    }); 

ご覧のとおり、返されたOKを処理するためにアプリで使用していたjavaScriptがあります。ただし、このスクリプトが起動すると、ブラウザはファイルをダウンロードしません。何か案は?

答えて

0

Get(string id)メソッドでは、HttpStatusCodeの代わりにHttpResponseMessageを返します。また、ASP.net Web APIは、HttpContext.Current.Response(いくつかのウィザードコードなし)の状態を保証しません。あなたは、Get(HttpRequestMessageリクエスト、文字列ID)に署名を変更し、request.CreateResponse(statusCode、data)のように何かをすることができます。