我正在尝试保护文件夹中的文件,以便只有具有特定角色的特定用户才能访问这些文件。
我正在使用ASP.Net MVC 4.5,Identity Framework并且知道您曾经能够编写一个HTTPHandler,它将位于请求管道中并为您提供一个钩子来处理请求。
由于某种原因,这似乎在ASP.Net MVC中不起作用。
using System;
using System.Web;
using System.Web.Security;
using System.IO;
using Microsoft.AspNet.Identity;
namespace Test.Handlers
{
/// <summary>
/// Handles processing requests for protected web application files, such as reports/*.pdf
/// The reports are checked by the user role to determine access.
/// </summary>
public class FileProtectionHandler : IHttpHandler
{
public bool IsReusable
{
get { return false; }
}
public void ProcessRequest(HttpContext context)
{
switch (context.Request.HttpMethod)
{
case "GET":
{
// Is the user logged-in?
if (!context.User.Identity.IsAuthenticated)
{
FormsAuthentication.RedirectToLoginPage();
return;
}
string requestedFile = context.Server.MapPath(context.Request.FilePath);
// Verify the user has access to the User role.
if (context.User.IsInRole("Admin") || context.User.IsInRole("Role1") || context.User.IsInRole("Rol2") || context.User.IsInRole("Role3") || context.User.IsInRole("Role4"))
{
SendContentTypeAndFile(context, requestedFile);
}
else
{
// Deny access, redirect to error page or back to login page.
context.Response.Redirect("~/login");
//FormsAuthentication.RedirectToLoginPage();
}
break;
}
}
}
private HttpContext SendContentTypeAndFile(HttpContext context, String strFile)
{
context.Response.ContentType = GetContentType(strFile);
context.Response.TransmitFile(strFile);
context.Response.End();
return context;
}
private string GetContentType(string filename)
{
// used to set the encoding for the reponse stream
string res = null;
FileInfo fileinfo = new FileInfo(filename);
if (fileinfo.Exists)
{
switch (fileinfo.Extension.Remove(0, 1).ToLower())
{
case "pdf":
{
res = "application/pdf";
break;
}
}
return res;
}
return null;
}
}
}