コード例 #1
0
        /// <summary>
        /// Serializes the data using the specified IDataWriter
        /// </summary>
        /// <param name="context">ControllerContext</param>
        public override void ExecuteResult(ControllerContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }

            HttpRequestBase  request  = context.HttpContext.Request;
            HttpResponseBase response = context.HttpContext.Response;

            IDataWriter writer = this.Provider.Find(request.Headers["Accept"], request.Headers["Content-Type"]);

            if (writer == null)
            {
                writer = this.Provider.Find(request.RawUrl);
            }
            if (writer == null)
            {
                writer = this.Provider.DefaultDataWriter;
            }
            if (writer == null)
            {
                throw new InvalidOperationException("No available IDataWriter implementations");
            }

            // need this to write out custom error objects
            response.TrySkipIisCustomErrors = true;

            if (this.HttpStatusCode != default(HttpStatusCode))
            {
                response.StatusCode = (int)this.HttpStatusCode;
            }

            if (String.IsNullOrEmpty(writer.ContentType))
            {
                // use the default content type
                response.ContentType = DataResult.DefaultContentType;
            }
            else
            {
                // set the response content type
                response.ContentType = writer.ContentType;
            }

            if (writer.ContentEncoding != null)
            {
                // set the response content encoding
                response.ContentEncoding = writer.ContentEncoding;
            }

            string ext      = writer.FileExtension;
            string filename = this.Filename;

            if (!String.IsNullOrEmpty(ext) ||
                !String.IsNullOrEmpty(filename))
            {
                if (String.IsNullOrEmpty(filename))
                {
                    filename = request.RawUrl;
                }
                filename = this.ScrubFilename(filename, ext ?? String.Empty);

                // this helps IE determine the Content-Type
                // http://tools.ietf.org/html/rfc2183#section-2.3
                ContentDisposition disposition = new ContentDisposition
                {
                    Inline   = true,
                    FileName = filename
                };
                response.AddHeader("Content-Disposition", disposition.ToString());
            }

            if (this.Data != null)
            {
                writer.Serialize(response.Output, this.Data);
            }
        }