Steven Chou
Steven Chou

Reputation: 2215

.net MVC:How do I serve static files only to authorized users

There are static files in my website like:

http://myurl.com/Content/a.html

http://myurl.com/Content/b.html

... etc

I want to verify the user's authentication when access. The authentication should be check by database's data.

My framework:ASP.NET MVC5

Upvotes: 1

Views: 3038

Answers (4)

Khizar Javed
Khizar Javed

Reputation: 21

Create web.config file in your static folder and insert this code.

<configuration>
  <system.web>
    <authorization>
      <deny users="?"/>
    </authorization>
  </system.web>
</configuration>

Upvotes: 2

Steven Chou
Steven Chou

Reputation: 2215

I finally solved this problem by this way, a important thing is I must to replace the static file's relative path with absolute path.

Upvotes: 0

KRob
KRob

Reputation: 389

Make sure users are authenticated by using the authorization element in your web.config. If all your static pages are in a folder named StaticPages, add a web.config file to that folder and insert the code below.

<location path="/StaticPages">
 <system.web>
  <authorization>
    <deny users="?"/>
  </authorization>
</system.web>

https://msdn.microsoft.com/en-us/library/8d82143t(v=vs.85).aspx

Upvotes: 2

FindOut_Quran
FindOut_Quran

Reputation: 768

Instead of putting your files in the traditional method /myserver/myfile.html, consider adding an action which returns the file after authinticating the user:

[Authorize]
public ActionResult GetFile(string name)
{
   // return the file
}

You may also use OutputCache attribute to cache your static file so that it is not being requested every time (if you are sure your file contents will not be changed)

Upvotes: 0

Related Questions