Serving static file on ASP.NET MVC (C#)

2019-07-13 04:07发布

问题:

I am completely new to .NET framework and i would like to know what is the best way to serve static content and to access user generated content.

Suppose i have the following files:

logo.jpg
document.pdf
etc.doc

Where should i put this (on which folders) ? And how do i access it?

Lastly, taking it into another level. Suppose i have a web apps that allows user to upload a document (let say some pics). What i would like to know is how should the structure of my folder/directory look like?

normaly in django / CI i would have a folder as follows:

application/{all-web-app-related-folder-and-file-goes-here} uploads/{all-related-user-generated-content-goes-here-categorized-by-file-type} assets/{css-javascript-document-would-go-here}

note: i haven't done anything or made any attempt to it. Simply because i have no idea how to access try static content. I once tried to access the *.css or *.js files located inside Content/Scripts folder.

i.e: localhost:12345/Scripts/jquery.js

It turns out, it is not a straightforward process in ASP.NET MVC

Oh by the way, in certain occasion, i would also like to access my images from my css file instead. Which raises yet another confusion to me.

EDIT 1: I read the following article

http://www.c-sharpcorner.com/uploadfile/dhananjaycoder/working-with-images-in-Asp-Net-mvc-framework/

however it is not applicable to my current version of MVC (i am using MVC 5)

EDIT 2: So, this is what i have been experimenting so far

  1. I created a folder called Assets on the root directory (same level as Models, Controllers, etc).
  2. Inside Asset i create sub-folders (i.e. images, documents, etc)
  3. Then i want to access those file directly from my views i would go like this:

    img src="@Url.Content("~/Asset/images/picture.png")"

The above example is appropriate if i want to access image file.

I however not sure if this is the ideal way to do it. It is however, the simplest solution i can come across at the moment (or should i say, rather naive).

Any hints would be appreciated.

回答1:

ASP.NET MVC allows static file serving by default. Instead of using @URL.Content directly write the path starting with / denoting the root folder

<img src="/Asset/images/picture.png" />