默認情況下,.NET身份驗證在靜態文件(如pdf)上不起作用。
如果用戶通過身份驗證,則需要實施HTTP處理程序來爲您的文件提供服務。
聽起來就像您當前的身份驗證已設置並正常工作,因此我不會詳細介紹設置的基本知識。
下面是一個適用於從Kory貝克爾的有價值的文章在這裏拍攝的場景中的相關代碼:
http://www.primaryobjects.com/2009/11/11/securing-pdf-files-in-asp-net-with-custom-http-handlers
你顯然需要改變的路徑,命名空間和邏輯,以滿足您的環境中(例如IIS版本)和/或特定的文件類型要求。
第1步 - 創建一個實現IHttpHandler的
public class FileProtectionHandler : IHttpHandler
{
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("Security Alerts - Admin"))
{
SendContentTypeAndFile(context, requestedFile);
}
else
{
// Deny access, redirect to error page or back to login page.
context.Response.Redirect("~/User/AccessDenied.aspx");
}
break;
}
}
}
public bool IsReusable { get; private set; }
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;
}
}
步驟2 FileProtectionHandler類 - 下面的章節添加到您的web.config文件(用適當的路徑/名稱空間的修改)
<httpHandlers>
...
<add path="*/User/Documents/*.pdf" verb="*" validate="true" type="CustomFileHandlerDemo.Handlers.FileProtectionHandler" />
</httpHandlers>
<system.webServer>
...
<handlers>
<add name="PDF" path="*.pdf" verb="*" type="CustomFileHandlerDemo.Handlers.FileProtectionHandler" resourceType="Unspecified" />
...
</handlers>
</system.webServer>
謝謝@Scotty - 我會試試這個,讓你知道它是怎麼回事。 – KlydeMonroe
嗨@Scotty - 我一直在執行上面提到的例子,並且它似乎沒有工作。我創建了一個名爲'Handlers'的新目錄,並創建了類'FileProtectionHandler',並將重定向更改爲我的應用程序的Login.aspx。然後,我將這些位添加到我的應用程序主web.config文件中 - 更改路徑以適合我的應用程序'*/documents/*。pdf'和type ='Alerts.Handlers.FileProtectionHandler',並且我使用IIS7,因此添加了Handler映射到這個。我現在正在和HTTP 500.23錯誤,有什麼建議嗎? – KlydeMonroe
我設法通過在我的web配置文件中的處理程序標記之前添加 -來實現此目的。感謝您的幫助 –
KlydeMonroe