簡體   English   中英

如何從(jquery)Asp.Net webApi檢索文件,並獲得Asp.Net Identity授權

[英]How to retrieve files from (jquery) Asp.Net webApi, authorized with Asp.Net Identity

也許有一個非常簡單的解決方案...但是我看過的很多線程都無法解決我的問題...我會盡量保持清晰。

在Asp.Net WebApi項目上,當前看起來像“ DownloadController”:

private HttpResponseMessage CreateFileResponse(string fileName, string originalName, List<string> allowedMimes)
    {
        // see if file exists
        if (!_FileProvider.Exists(fileName))
        {
            return Request.CreateResponse(HttpStatusCode.NotFound);
        }

        // retrieve mimeType
        string mimeType = MimeMapping.GetMimeMapping(fileName);
        if (!allowedMimes.Contains(mimeType))
        {
            mimeType = _generalMimeType;
        }

        // open the file
        FileStream fileStream = _FileProvider.Open(fileName);

        // create the response
        var response = new HttpResponseMessage();
        response.Content = new StreamContent(fileStream);
        response.Content.Headers.ContentType = new MediaTypeHeaderValue(mimeType);
        response.Content.Headers.ContentLength = _FileProvider.GetLength(fileName);

        // if the mimetype is not allowed, download as attachment
        if (mimeType == _generalMimeType)
        {
            response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment");
            response.Content.Headers.ContentDisposition.FileName = originalName;
        }

        return response;
    }

    //for understanding the above
    public DownloadController()
    {
        _FileProvider = new FileProvider();
    }

    public interface IFileProvider
    {
        bool Exists(string name);
        FileStream Open(string name);
        long GetLength(string name);
    }

當對控制器上的特定路由執行簡單的HTTP GET(僅在瀏覽器中為url)時,這段代碼可以完美地工作。

    [Route("Download/Document/{documentid}")]
    public HttpResponseMessage GetDocument(Guid documentid)
    {
       -
       -
       -
       -
   return this.CreateFileResponse(fileName, document.filename, allowedMimes);    
    }

但是現在所有的控制器都被asp.net Identity的[Authorize]字段授權。 現在,所有請求都需要一個Authorization字段,其中的標頭中包含一個令牌(Bearer“令牌”)。 現在,幾乎所有請求都是通過jquery完成的,您可以在其中簡單地添加標頭字段。 但是,對於下載文件,這並未完成。 通過在DownloadController上使用帶有令牌頭的jquery可以給出響應:

PNG NG IHDR.ssRGB.gAMA.a pHYs..o .......

當我使用令牌進行請求時,提琴手和郵遞員也能夠顯示真實圖像。 (不知道pdf文件或其他文件)

但是,使用我在stackoverflow上嘗試過的某些javascript解決方案設置此數據將無法正常工作。...圖像始終不可用。有人可以提供解決方案來從javascript設置此數據嗎? 當然還有其他解決方案。

Fiddler截獲的響應: Fiddler截獲的回應

有諸如groupdocs之類的工具,可將流轉換為htmlresponse,圖像和本機,您可以使用它們在html代碼中進行呈現。 您可以在api調用中執行此操作,以便將響應作為字節流發送。 groupdocs-library

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM