Asp.net mvc 4 使用MVC操作过滤器返回图像

Asp.net mvc 4 使用MVC操作过滤器返回图像,asp.net-mvc-4,Asp.net Mvc 4,我有一个场景,在点击特定动作之前使用动作过滤器返回图像。我们可以使用动作过滤器来实现这一点吗?在这里,我们将图像作为内容返回,如果我们在url中遇到任何图像文件,则传递到相应的操作。是的,您可以。把这个看作是一个例子: public class MyFileFilterAttribute : ActionFilterAttribute { public override void OnActionExecuting(ActionExecutingContext filterContext

我有一个场景,在点击特定动作之前使用动作过滤器返回图像。我们可以使用动作过滤器来实现这一点吗?在这里,我们将图像作为内容返回,如果我们在url中遇到任何图像文件,则传递到相应的操作。

是的,您可以。把这个看作是一个例子:

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
}