我有在使用特定操作之前使用操作过滤器返回图像的方案。我们可以使用动作过滤器来实现吗?如果我们在url中遇到任何图像文件,我们将图像作为内容返回,否则传递给相应的操作。
答案 0 :(得分:0)
是的,你可以。以此为例:
public class MyFileFilterAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
// imagine in your route data you have a key named file
// which contain file name
// if you want access to request url to check if it is a file use
// filterContext.HttpContext.Request.AppRelativeCurrentExecutionFilePath
// property instead
if (filterContext.RouteData.Values.ContainsKey("file"))
{
// very simple example how to find file on the server
string physicalFilePath=HttpContext.Current.Server.MapPath(
filterContext.RouteData.Values["file"].ToString());
// if your url matches and you found a file set
// filterContext.Result value otherwise nothing.
if(File.Exists(physicalFilePath))
{
// also you must send a proper content type for each file.
filterContext.Result = new FilePathResult(physicalFilePath, "YourFileContentType");
}
}
}
}
最后,只需使用您的属性:
[MyFileFilter]
public ActionResult MyAction()
{
// your code
}