下載文件我正在使用ASP.NET Web API構建一個具有下載文件方法的Web服務(和站點)的原型。當前端用戶按下導出按鈕時,由控制器創建並接收jQuery ajax GET請求,然後調用名爲Excel的方法(如下所示)。該方法運行沒有任何問題並完成。當我在標題中查看Chrome時(請參閱https://skydrive.live.com/redir?resid=2D85E5C937AC2BF9!77093),它會收到響應(就我而言)所有正確的標題。Web Api將不會使用jQuery Ajax和Basic Auth
我正在使用基本身份驗證,因此用戶證書使用http授權標頭傳輸,我已使用Ajax選項手動添加到每個jQuery Ajax請求中。
var excelRequest = $.ajax({
url: 'http://localhost:59390/api/mycontroller/excel',
cache: false,
type: 'GET',
data: gridString,
dataType: 'json',
contentType: 'application/json; charset=utf-8'
});
$.ajaxSetup({
beforeSend: function (xhr) {
SetAuthRequestHeader(xhr)
}
});
function SetAuthRequestHeader(jqXHR) {
var usr = "Gebruiker2"; // TODO: Change, this is for testing only.
var pw = "Wachtwoord23";
jqXHR.setRequestHeader("Authorization", "Basic " + Base64.encode(usr + ":" + pw));
}
我的原型有一些特點,我應該提到:
使用基本身份驗證在授權頭
Web服務和Web網站,其中調用的服務是不同的域,所以我使用CORS並將以下內容添加到web.config中
<httpProtocol> <customHeaders> <add name="Access-Control-Allow-Origin" value="*" /> <add name="access-control-allow-headers" value="Content-Type, Authorization, Accept" /> <add name="Access-Control-Allow-Methods" value="GET, POST, PUT, DELETE, OPTIONS" </customHeaders> </httpProtocol>
下面顯示的是整個Excel方法。
[HttpGet]
// Get api/myController/excel
public HttpResponseMessage Excel(string sidx, string sord, int page, int rows, string Depot, string PDID, string User, string Property, string Value)
{
if (AuthHelper.AuthService.HasValidCredentials(Request))
{
var gridResult = this.GetDataJqGridFormat(sidx, sord, page, rows, Depot, PDID, User, Property, Value);
// Generate a HTML table.
StringBuilder builder = new StringBuilder();
// We create a html table:
builder.Append("<table border=1>");
builder.Append("<tr><td>DEPOT</td>");
builder.Append("<td>PDID</td>");
builder.Append("<td>USER</td>");
builder.Append("<td>PROPERTY</td>");
builder.Append("<td>VALUE</td></tr>");
// Create response from anonymous type
foreach (var item in gridResult.rows)
{
builder.Append("</tr>");
builder.Append("<tr>");
builder.Append("<td>" + item.cell[0] + "</td>");
builder.Append("<td>" + item.cell[2] + "</td>");
builder.Append("<td>" + item.cell[3] + "</td>");
builder.Append("<td>" + item.cell[4] + "</td>");
builder.Append("<td>" + item.cell[5] + "</td>");
}
builder.Append("</table>");
HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK);
result.Content = new StringContent(builder.ToString());
result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment");
result.Content.Headers.ContentDisposition.FileName = "file.xls";
return result;
}
else
{
throw ForbiddenResponseMessage();
}
}
這是標題也應該返回文件: https://skydrive.live.com/redir?resid=2D85E5C937AC2BF9!77093
我想是有文件下載,當我打電話,它指向的Excel方法的URL。我不明白爲什麼它不會下載。這種方式甚至可以下載文件嗎?