Как вызвать метод веб-API для загрузки файла, когда веб-API использует авторизацию на основе токена?Мы можем загрузить файл, если у нас нет полномочий и если мы даем window.location.href = "/ api / CaseDetailsSvc / DownloadCaseDoc? StrFileName =" + fileName.Но мы бы хотели, чтобы только авторизованные пользователи могли вызывать этот метод веб-API.Как это решить?
Вот код, который у нас есть:
[Authorize(Roles = "RspCaseEdit")]
public class CaseDetailsSvcController : ApiController
{
[HttpGet]
public HttpResponseMessage DownloadCaseDoc(string strFileName)
{
HttpResponseMessage result = null;
string fullPath = "CaseDocs\\"+strFileName;
if (!File.Exists(fullPath))
{
result = Request.CreateResponse(HttpStatusCode.NotFound);
}
else
{
// Serve the file to the client
result = Request.CreateResponse(HttpStatusCode.OK);
result.Content = new StreamContent(new FileStream(fullPath, FileMode.Open, FileAccess.Read));
result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
result.Content.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment");
result.Content.Headers.ContentDisposition.FileName = strFileName;
}
return result;
}
}
//angularJs service
this.DownloadCaseDoc = function (fileName) {
var rep = $http({
url: "/api/CaseDetailsSvc/DownloadCaseDoc?strFileName=" + fileName,
method: 'GET',
headers: authHeads,
});
return rep;
};
//AngularJs controller
vm.downloadFile = function (fileName) {
var response = caseService.DownloadCaseDoc(fileName).then(function (resp) {
//What to write here to download the file.
}, function (error) {
console.log('here is your error', error)
});
}