首頁 >後端開發 >C++ >如何在ASP.NET MVC中控製文件顯示(查看或下載)?

如何在ASP.NET MVC中控製文件顯示(查看或下載)?

Barbara Streisand
Barbara Streisand原創
2025-01-31 13:56:09900瀏覽

How to Control File Display (View or Download) in ASP.NET MVC?

在ASP.NET MVC

>

FileResult>FileStreamResultContentDisposition>

>

> FileStreamResult>

> ASP.NET MVC應用程序通常需要將存儲在數據庫中的文件提供給用戶。 一個關鍵挑戰是為用戶提供控制這些文件的處理方式 - 無論是直接在瀏覽器中查看還是下載。
<code class="language-csharp">// Opens known types, downloads unknown types (incorrect filename/extension)
return new FileStreamResult(new MemoryStream(document.Data), document.ContentType);</code>
>。

>提供一個簡單的解決方案,但對於未知文件類型可能是不可靠的,通常默認為下載。 要獲得更健壯的控制,請考慮使用File或操縱ContentDisposition標題。

>
<code class="language-csharp">public ActionResult Download()
{
    var document = ...;
    var cd = new System.Net.Mime.ContentDisposition
    {
        FileName = document.FileName,
        Inline = false, // Forces download
    };
    Response.AppendHeader("Content-Disposition", cd.ToString());
    return File(document.Data, document.ContentType);
}</code>
使用

>提供妥協:ContentDispositionHeaderValue

<code class="language-csharp">public IActionResult Download()
{
    var document = ...;
    var cd = new ContentDispositionHeaderValue("attachment")
    {
        FileNameStar = document.FileName // Use FileNameStar for better encoding
    };
    Response.Headers.Add(HeaderNames.ContentDisposition, cd.ToString());
    return File(document.Data, document.ContentType);
}</code>
>不管文件類型如何,都可以使用自定義的

標題:

使用> 為了改善國際角色支持,建議班級:> 這些方法允許開發人員精確管理文件傳輸,確保用戶打算查看或下載文件。

以上是如何在ASP.NET MVC中控製文件顯示(查看或下載)?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn