コード例 #1
0
ファイル: PipelineConfig.cs プロジェクト: timgaunt/resizer
        public IAsyncTyrantCache GetAsyncCacheFor(HttpContext context, IAsyncResponsePlan plan)
        {
            IAsyncTyrantCache defaultCache = null;

            //Grab the last cache that claims it can process the request.
            foreach (IAsyncTyrantCache cache in c.Plugins.GetAll <IAsyncTyrantCache>())
            {
                if (cache.CanProcess(context, plan))
                {
                    defaultCache = cache;
                }
            }

            return(defaultCache);
        }
コード例 #2
0
        /// <summary>
        /// Generates the resized image to disk (if needed), then rewrites the request to that location.
        /// Perform 404 checking before calling this method. Assumes file exists.
        /// Called during PostAuthorizeRequest
        /// </summary>
        /// <param name="context"></param>
        /// <param name="ra"></param>
        /// <param name="vf"></param>
        protected virtual async Task HandleRequest(HttpContext context, HttpModuleRequestAssistant ra, IVirtualFileAsync vf)
        {
            if (!ra.CachingIndicated && !ra.ProcessingIndicated)
            {
                ra.ApplyRewrittenPath(); //This is needed for both physical and virtual files; only makes changes if needed.
                if (vf != null)
                {
                    ra.AssignSFH(); //Virtual files are not served in .NET 4.
                }
                return;
            }


            //Communicate to the MVC plugin this request should not be affected by the UrlRoutingModule.
            context.Items[conf.StopRoutingKey]  = true;
            context.Items[conf.ResponseArgsKey] = ""; //We are handling the request


            ra.EstimateResponseInfo();



            //Build CacheEventArgs
            var e = new AsyncResponsePlan();

            var modDate = (vf == null) ? System.IO.File.GetLastWriteTimeUtc(ra.RewrittenMappedPath) :
                          (vf is IVirtualFileWithModifiedDateAsync ? await((IVirtualFileWithModifiedDateAsync)vf).GetModifiedDateUTCAsync() : DateTime.MinValue);

            e.RequestCachingKey = ra.GenerateRequestCachingKey(modDate);

            var settings = new ResizeSettings(ra.RewrittenInstructions);

            e.RewrittenQuerystring   = settings;
            e.EstimatedContentType   = ra.EstimatedContentType;
            e.EstimatedFileExtension = ra.EstimatedFileExtension;



            //A delegate for accessing the source file
            e.OpenSourceStreamAsync = async delegate()
            {
                return((vf != null) ? await vf.OpenAsync() : File.Open(ra.RewrittenMappedPath, FileMode.Open, FileAccess.Read, FileShare.Read));
            };

            //Add delegate for writing the data stream
            e.CreateAndWriteResultAsync = async delegate(System.IO.Stream stream, IAsyncResponsePlan plan)
            {
                //This runs on a cache miss or cache invalid. This delegate is preventing from running in more
                //than one thread at a time for the specified cache key
                try
                {
                    if (!ra.ProcessingIndicated)
                    {
                        //Just duplicate the data
                        using (Stream source = await e.OpenSourceStreamAsync())
                            await source.CopyToAsync(stream); //4KiB buffer
                    }
                    else
                    {
                        MemoryStream inBuffer = null;
                        using (var sourceStream = vf != null ? await vf.OpenAsync() : File.Open(ra.RewrittenMappedPath, FileMode.Open, FileAccess.Read, FileShare.Read))
                        {
                            inBuffer = new MemoryStream(sourceStream.CanSeek ? (int)sourceStream.Length : 128 * 1024);
                            await sourceStream.CopyToAsync(inBuffer);
                        }
                        inBuffer.Seek(0, SeekOrigin.Begin);

                        var outBuffer = new MemoryStream(32 * 1024);

                        //Handle I/O portions of work asynchronously.
                        var j = new ImageJob
                        {
                            Instructions   = new Instructions(settings),
                            SourcePathData = vf != null ? vf.VirtualPath : ra.RewrittenVirtualPath,
                            Dest           = outBuffer,
                            Source         = inBuffer
                        };

                        await conf.GetImageBuilder().BuildAsync(j, int.MaxValue, CancellationToken.None);

                        outBuffer.Seek(0, SeekOrigin.Begin);
                        await outBuffer.CopyToAsync(stream);
                    }
                    ra.FireJobSuccess();
                    //Catch not found exceptions
                }
                catch (System.IO.FileNotFoundException notFound)
                {
                    if (notFound.Message.Contains(" assembly "))
                    {
                        throw;                                          //If an assembly is missing, it should be a 500, not a 404
                    }
                    //This will be called later, if at all.
                    ra.FireMissing();
                    throw new ImageMissingException("The specified resource could not be located", "File not found", notFound);
                }
                catch (System.IO.DirectoryNotFoundException notFound)
                {
                    ra.FireMissing();
                    throw new ImageMissingException("The specified resource could not be located", "File not found", notFound);
                }
                catch (Exception ex)
                {
                    ra.FireJobException(ex);
                    throw;
                }
            };



            //All bad from here down....
            context.Items[conf.ResponseArgsKey] = e; //store in context items

            //Fire events (for client-side caching plugins)
            conf.FirePreHandleImageAsync(this, context, e);

            //Pass the rest of the work off to the caching module. It will handle rewriting/redirecting and everything.
            //We handle request headers based on what is found in context.Items
            IAsyncTyrantCache cache = conf.GetAsyncCacheFor(context, e);

            //Verify we have a caching system
            if (cache == null)
            {
                throw new ImageProcessingException("Image Resizer: No async caching plugin was found for the request");
            }

            await cache.ProcessAsync(context, e);
        }