How to restrict access to a certain file in MVC

天大地大妈咪最大 提交于 2019-12-08 04:57:16

问题


I am using ASP.Net MVC, and I was wondering how can I restrict access to a certain file. I read about using [Authorize] but it applies to controllers and actions. I try to use within the web.config but its extremely advise not to do that cause MVC becomes confuse when seeing multiple .

My file is within the base of the application, e.g. /MyApp/MyFile. I would like to do is, when a user navigates to the file. The user will see, correct me if I'm wrong, the HTTP 401 error or something.


回答1:


In order to do this stick the files in a folder under App_Data which will prevent direct access and then you will need to create a controller to handle access to the file. First create a route:

routes.MapRoute("", "Files/{file}", new { controller = "File", action = "View" });

and then apply the Authorize attribute to the action and use

return File(...);

to actually return the file to the user.



来源:https://stackoverflow.com/questions/12797297/how-to-restrict-access-to-a-certain-file-in-mvc

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!