Returning a file to View/Download in ASP.NET MVC
public ActionResult Download()
{
var document = ...
var cd = new System.Net.Mime.ContentDisposition
{
// for example foo.bak
FileName = document.FileName,
// always prompt the user for downloading, set to true if you want
// the browser to try to show the file inline
Inline = false,
};
Response.AppendHeader("Content-Disposition", cd.ToString());
return File(document.Data, document.ContentType);
}
NOTE: This example code above fails to properly account for international characters in the filename. See RFC6266 for the relevant standardization. I believe recent versions of ASP.Net MVC's File()
method and the ContentDispositionHeaderValue
class properly accounts for this. - Oskar 2016-02-25
return a View and File in a single method in ASP.Net MVC
Please use like below.
ViewData["text"] = "text that you need to return";
ViewData["FileName"] = "Name of the file that you need to return";
ViewData["Filepath"] = "Path of the file that you need to return";
return View();
In your view you can use them like below
@{
var text = ViewData["text"];
var filename = ViewData["FileName"];
var filePath = ViewData["Filepath"];
}
If you need to done without using ViewData or ViewBage means please follow the below code.
There are 3 steps need to do for it.
Step 1:
Create a model class for it.
My model code
public class FileDetails
{
public string Text { get; set; }
public string FileName { get; set; }
public string Filepath { get; set; }
}
Step 2: Controller code to return view with FileDetails Model.
FileDetails Details = new FileDetails();
Details.Text = "text that you need to return";
Details.FileName = "Name of the file that you need to return";
Details.Filepath = "Path of the file that you need to return";
return View("ViewName", Details);
Step 3: Your View must contain the FileDetails model Header. like Below
@model YourProjectName.Models.FileDetails
The above code is must be at top of your view page where you need to use those details.
My View code
@{
var text = Model.Text;
var filename = Model.FileName;
var filePath = Model.Filepath;
}
Why is my file download from MVC controller returning HTTP 404
With a route template of [Route("r/[controller]/[action]")]
specified on the controller, the route for the ExportData
action becomes:
r/OtpLock/ExportData
Adding [HttpGet("export")]
to the ExportData
method appends an existing segment, export
, which changes its route to:
r/OtpLock/ExportData/export
This isn't the URL you're using for your AJAX calls, so the server responds with a 404.
To make this behave as you expect, there are a few options. e.g.:
- Use
[ActionName("export")]
instead of[HttpGet("export")]
. This has the effect of providingexport
as the value for[action]
, rather than the default, which is the name of the method,ExportData
. It also doesn't add anything extra to the route defined at the controller level. - Remove the
[HttpGet("export")]
attribute and rename theExportData
action at the code level, by renaming the method toExport
instead ofExportData
. - You might be able to remove both the
[Route(...)]
attribute from the controller and the[HttpGet(...)]
attribute from the action. This would revert to using convention-based routing, which you've set up withMapAreaControllerRoute
. This would also require either #1 or #2 above, but I'm not 100% on whether this will work for your setup.
ASP.NET MVC: returning plaintext file to download from controller method
Use the File method on the controller class to return a FileResult
public ActionResult ViewHL7( int id )
{
...
return File( Encoding.UTF8.GetBytes( someLongTextForDownLoad ),
"text/plain",
string.Format( "{0}.hl7", id ) );
}
How can I allow logged in users be able to direct download file from an ASP.NET MVC application
It depends that how would you like to implement this scenario :
First scenario :
you could put your download links inside these block of code, to prevent from showing to unauthorized users.
View page :
@if (Utility.CheckActionPermission("ActionName", "ControllerName", "AreaName"))
{
// your download link should be here
}
Controller :
public static bool CheckActionPermission(string actionName, string controllerName, string areaName)
{
var accessUrl = string.Concat(areaName, "/", controllerName, "/", actionName);
return ((CustomPrincipal)HttpContext.Current.User).Access.Any(a => a.Url == accessUrl);
}
Second scenario :
Put all of your links freely to show to every user but you need to validate the user's authority when the download link clicked :
View:
@Html.ActionLink("File Name", "DownloadFile", "ControllerName", new { fileName= @Model.FileName }, null)
Controller
[Authorize]
public static bool DownloadFile(string fileName)
{
var filePath = Path.Combine(PathConstants.DownloadFolder, fileName);
//some code to download the file
}
Related Topics
Copy Few Items from One List to Another List of Same Type in C#
C# How to Split a List in Two Using Linq
Could Not Start Windows Service, Error 1064
Kill Child Process When Parent Process Is Killed
Console.Writeline Does Not Show Up in Output Window
Update Value in Datatable from Another Datatable
Accessing a Shared File (Unc) from a Remote, Non-Trusted Domain With Credentials
How to Change a Image on a Button Using Windows Forms
Where Is the Postasjsonasync Method in ASP.NET Core
How to Return a File (Filecontentresult) in ASP.NET Webapi
How to Loop Through Each and Every Row, Put Value in Gridview Column Cells
How Does Httpcontext.Current.User.Identity.Name Know Which Usernames Exist
Using Formflow Dialog in Bot Framework
Newtonsoft Json Dynamic Property Name
How to Disable Cursor in Textbox
Using X-Alt-Desc/Applying HTML to Calendar Invites in Outlook