简体   繁体   English

从ASP.NET项目使用网页下载文件

[英]Download file using webpage from ASP.NET project

I am follow this articles in order to build simple web site. 我将按照这篇文章来构建简单的网站。 i have database with an objects, each object represent file on dist and several properties (size, name etc...) and i have several questions: 我有一个对象数据库,每个对象代表dist上的文件和几个属性(大小,名称等...),我有几个问题:

  1. After add the controller like in this article (min 1:45) after run my application it navigate not the my home page but into this index page and only after press Home button i can see my home page - how to fix it ? 在运行了我的应用程序之后,按照本文(最低1:45)的方式添加了控制器之后,它不导航我的主页而是导航到该索引页面,并且仅在按下“主页”按钮后我才能看到我的主页-如何解决?

  2. in this example each person have several actions: delete, update, details... I only want to have the option Download to download this file into my system (all the files location is in network folder with access) - how can i do that ? 在此示例中,每个人都有几个操作:删除,更新,详细信息...我只想选择Download以将该文件下载到我的系统中(所有文件位置都在具有访问权限的网络文件夹中)-我该怎么做?

Index.schtml: Index.schtml:

@{
    ViewBag.Title = "Home Page";  
}


<div class="hero-unit">
    <h1>Automation Captures <image>
                                <img src="~/img/wireshark_logo.png" /></image></h1>
    <p class="lead">Automation captures made by running robors.</p>
    <p><a href="http://asp.net" class="btn btn-primary btn-large">Learn more &raquo;</a></p>
</div>
<div class="row">
    <div class="span4">
        <h2>button1</h2>
        <p>ASP.NET MVC gives you a powerful, patterns-based way to build dynamic websites that
        enables a clean separation of concerns and gives you full control over markup
        for enjoyable, agile development.</p>
        <p><a href="/WebMail " class="btn btn-primary btn-large">Click here &raquo;</a></p>
    </div>
    <div class="span4">
        <h2>button2</h2>
        <p>NuGet is a free Visual Studio extension that makes it easy to add, remove, and update libraries and tools in Visual Studio projects.</p>
        <p><a href="http://asp.net" class="btn btn-primary btn-large">Click here &raquo;</a></p>
    </div>
    <div class="span4">
        <h2>button3</h2>
        <p>You can easily find a web hosting company that offers the right mix of features and price for your applications.</p>
        <p><a href="http://asp.net" class="btn btn-primary btn-large">Click here &raquo;</a></p>
    </div>
</div>
<div class="row">
    <div class="span4">
        <h2>button4</h2>
        <p>
            ASP.NET MVC gives you a powerful, patterns-based way to build dynamic websites that
            enables a clean separation of concerns and gives you full control over markup
            for enjoyable, agile development.
        </p>
        <p><a href="http://asp.net" class="btn btn-primary btn-large">Click here &raquo;</a></p>
    </div>
    <div class="span4">
        <h2>button5</h2>
        <p>NuGet is a free Visual Studio extension that makes it easy to add, remove, and update libraries and tools in Visual Studio projects.</p>
        <p><a href="http://asp.net" class="btn btn-primary btn-large">Click here &raquo;</a></p>
    </div>
    <div class="span4">
        <h2>button6</h2>
        <p>You can easily find a web hosting company that offers the right mix of features and price for your applications.</p>
        <p><a href="http://asp.net" class="btn btn-primary btn-large">Click here &raquo;</a></p>
    </div>
</div>

Home controller 家庭控制器

public class NewController : Controller
{
    private MyObjectDBContext db = new MyObjectDBContext();

    // GET: /WebMail/
    public ActionResult Index()
    {
        return View(db.MyObjects.ToList());
    }

    // GET: /WebMail/Details/5
    public ActionResult Details(int? id)
    {
        if (id == null)
        {
            return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
        }
        MyObject MyObject = db.MyObjects.Find(id);
        if (MyObject == null)
        {
            return HttpNotFound();
        }
        return View(MyObject);
    }

    // GET: /WebMail/Create
    public ActionResult Create()
    {
        return View();
    }

My new controller 我的新控制器

public class NewController : Controller
{
    private MyObjectDBContext db = new MyObjectDBContext();

    // GET: /MyObject/
    public ActionResult Index()
    {
        return View(db.MyObjects.ToList());
    }

    // GET: /MyObject/Details/5
    public ActionResult Details(int? id)
    {
        if (id == null)
        {
            return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
        }
        MyObject MyObject = db.MyObjects.Find(id);
        if (MyObject == null)
        {
            return HttpNotFound();
        }
        return View(MyObject);
    }

    // GET: /MyObject/Create
    public ActionResult Create()
    {
        return View();
    }

    // POST: /MyObject/Create
    // To protect from over posting attacks, please enable the specific properties you want to bind to, for 
    // more details see http://go.microsoft.com/fwlink/?LinkId=317598.
    // 
    // Example: public ActionResult Update([Bind(Include="ExampleProperty1,ExampleProperty2")] Model model)
    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Create(MyObject MyObject)
    {
        if (ModelState.IsValid)
        {
            db.MyObjects.Add(MyObject);
            db.SaveChanges();
            return RedirectToAction("Index");
        }

        return View(MyObject);
    }

    // GET: /MyObject/Edit/5
    public ActionResult Edit(int? id)
    {
        if (id == null)
        {
            return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
        }
        MyObject MyObject = db.MyObjects.Find(id);
        if (MyObject == null)
        {
            return HttpNotFound();
        }
        return View(MyObject);
    }

    // POST: /MyObject/Edit/5
    // To protect from over posting attacks, please enable the specific properties you want to bind to, for 
    // more details see http://go.microsoft.com/fwlink/?LinkId=317598.
    // 
    // Example: public ActionResult Update([Bind(Include="ExampleProperty1,ExampleProperty2")] Model model)
    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Edit(MyObject MyObject)
    {
        if (ModelState.IsValid)
        {
            db.Entry(MyObject).State = EntityState.Modified;
            db.SaveChanges();
            return RedirectToAction("Index");
        }
        return View(MyObject);
    }

    // GET: /MyObject/Delete/5
    public ActionResult Delete(int? id)
    {
        if (id == null)
        {
            return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
        }
        MyObject MyObject = db.MyObjects.Find(id);
        if (MyObject == null)
        {
            return HttpNotFound();
        }
        return View(MyObject);
    }

    // POST: /MyObject/Delete/5
    [HttpPost, ActionName("Delete")]
    [ValidateAntiForgeryToken]
    public ActionResult DeleteConfirmed(int id)
    {
        MyObject MyObject = db.MyObjects.Find(id);
        db.MyObjects.Remove(MyObject);
        db.SaveChanges();
        return RedirectToAction("Index");
    }

    protected override void Dispose(bool disposing)
    {
        db.Dispose();
        base.Dispose(disposing);
    }
}

Global.ASPX Global.ASPX

public class MvcApplication : System.Web.HttpApplication
{
    private CaptureDBContext db = new CaptureDBContext();
    protected void Application_Start()
    {
        AreaRegistration.RegisterAllAreas();
        FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
        RouteConfig.RegisterRoutes(RouteTable.Routes);
        BundleConfig.RegisterBundles(BundleTable.Bundles);
    }
}

As you have written your code in new controller and use it to show default home page of the site,you need to change route in global.asax or in RouteConfig file(whereever you are registering your routes) with this, 在新控制器中编写代码并使用它显示站点的默认主页时,您需要在global.asaxRouteConfig文件(无论您要注册的路由)中更改路由,

    routes.MapRoute(
                    name: "Default",
                    url: "{controller}/{action}/{id}",
                    defaults: new { controller = "New", action = "Index", 
                                   id = UrlParameter.Optional }
                );

for downloading a file you'll require a controller action to return FileResult 下载文件,您需要执行控制器操作以返回FileResult

public FileResult Download()
{
    byte[] fileBytes =/*fetch your file here and read it*/;
    string fileName = "example";
    return File(fileBytes, System.Net.Mime.MediaTypeNames.Application.Octet,
                  fileName);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM