コード例 #1
0
        public void ToString_UseDifferentMediaTypes_AllSerializedCorrectly()
        {
            var mediaType = new MediaTypeHeaderValue("text/plain");

            Assert.Equal("text/plain", mediaType.ToString());

            mediaType.Charset = "utf-8";
            Assert.Equal("text/plain; charset=utf-8", mediaType.ToString());

            mediaType.Parameters.Add(new NameValueHeaderValue("custom", "\"custom value\""));
            Assert.Equal("text/plain; charset=utf-8; custom=\"custom value\"", mediaType.ToString());

            mediaType.Charset = null;
            Assert.Equal("text/plain; custom=\"custom value\"", mediaType.ToString());
        }
コード例 #2
0
        public async static Task ReturnScript(HttpContext context, string scriptKey, string contentType)
        {
            var dynamicScript = DynamicScriptManager.GetScript(scriptKey);
            if (dynamicScript == null)
            {
                context.Response.StatusCode = (int)HttpStatusCode.NotFound;
                await context.Response.WriteAsync("File not found!");
            }

            var mediaType = new MediaTypeHeaderValue(contentType);
            mediaType.Encoding = System.Text.Encoding.UTF8;
            context.Response.ContentType = mediaType.ToString();

            var responseHeaders = context.Response.GetTypedHeaders();
            var cacheControl = responseHeaders.CacheControl = new CacheControlHeaderValue();
            cacheControl.MaxAge = TimeSpan.FromDays(365);
            cacheControl.Private = true;
            cacheControl.MustRevalidate = false;

            var supportsGzip = dynamicScript.CompressedBytes != null &&
                context.Request.GetTypedHeaders().AcceptEncoding.ToString()
                    .IndexOf("gzip", StringComparison.OrdinalIgnoreCase) >= 0;

            byte[] contentBytes;
            if (supportsGzip)
            {
                context.Response.Headers["Content-Encoding"] = "gzip";
                contentBytes = dynamicScript.CompressedBytes;
            }
            else
                contentBytes = dynamicScript.UncompressedBytes;

            await WriteWithIfModifiedSinceControl(context, contentBytes, dynamicScript.Time);
        }
コード例 #3
0
ファイル: ViewExecutor.cs プロジェクト: ryanbrandenburg/Mvc
        /// <summary>
        /// Asynchronously renders the specified <paramref name="view"/> to the response body.
        /// </summary>
        /// <param name="view">The <see cref="IView"/> to render.</param>
        /// <param name="actionContext">The <see cref="ActionContext"/> for the current executing action.</param>
        /// <param name="viewData">The <see cref="ViewDataDictionary"/> for the view being rendered.</param>
        /// <param name="tempData">The <see cref="ITempDataDictionary"/> for the view being rendered.</param>
        /// <returns>A <see cref="Task"/> that represents the asynchronous rendering.</returns>
        public static async Task ExecuteAsync([NotNull] IView view,
                                              [NotNull] ActionContext actionContext,
                                              [NotNull] ViewDataDictionary viewData,
                                              [NotNull] ITempDataDictionary tempData,
                                              [NotNull] HtmlHelperOptions htmlHelperOptions,
                                              MediaTypeHeaderValue contentType)
        {
            var response = actionContext.HttpContext.Response;

            contentType = contentType ?? DefaultContentType;
            if (contentType.Encoding == null)
            {
                // Do not modify the user supplied content type, so copy it instead
                contentType = contentType.Copy();
                contentType.Encoding = Encoding.UTF8;
            }

            response.ContentType = contentType.ToString();

            using (var writer = new HttpResponseStreamWriter(response.Body, contentType.Encoding))
            {
                var viewContext = new ViewContext(
                    actionContext,
                    view,
                    viewData,
                    tempData,
                    writer,
                    htmlHelperOptions);

                await view.RenderAsync(viewContext);
            }
        }
コード例 #4
0
        /// <summary>
        /// Gets the content type and encoding that need to be used for the response.
        /// The priority for selecting the content type is:
        /// 1. ContentType property set on the action result
        /// 2. <see cref="HttpResponse.ContentType"/> property set on <see cref="HttpResponse"/>
        /// 3. Default content type set on the action result
        /// </summary>
        /// <remarks>
        /// The user supplied content type is not modified and is used as is. For example, if user
        /// sets the content type to be "text/plain" without any encoding, then the default content type's
        /// encoding is used to write the response and the ContentType header is set to be "text/plain" without any
        /// "charset" information.
        /// </remarks>
        /// <param name="actionResultContentType">ContentType set on the action result</param>
        /// <param name="httpResponseContentType"><see cref="HttpResponse.ContentType"/> property set
        /// on <see cref="HttpResponse"/></param>
        /// <param name="defaultContentType">The default content type of the action result.</param>
        /// <param name="resolvedContentType">The content type to be used for the response content type header</param>
        /// <param name="resolvedContentTypeEncoding">Encoding to be used for writing the response</param>
        public static void ResolveContentTypeAndEncoding(
            MediaTypeHeaderValue actionResultContentType,
            string httpResponseContentType,
            MediaTypeHeaderValue defaultContentType,
            out string resolvedContentType,
            out Encoding resolvedContentTypeEncoding)
        {
            Debug.Assert(defaultContentType != null);
            Debug.Assert(defaultContentType.Encoding != null);

            // 1. User sets the ContentType property on the action result
            if (actionResultContentType != null)
            {
                resolvedContentType = actionResultContentType.ToString();
                resolvedContentTypeEncoding = actionResultContentType.Encoding ?? defaultContentType.Encoding;
                return;
            }

            // 2. User sets the ContentType property on the http response directly
            if (!string.IsNullOrEmpty(httpResponseContentType))
            {
                MediaTypeHeaderValue mediaType;
                if (MediaTypeHeaderValue.TryParse(httpResponseContentType, out mediaType))
                {
                    resolvedContentType = httpResponseContentType;
                    resolvedContentTypeEncoding = mediaType.Encoding ?? defaultContentType.Encoding;
                }
                else
                {
                    resolvedContentType = httpResponseContentType;
                    resolvedContentTypeEncoding = defaultContentType.Encoding;
                }

                return;
            }

            // 3. Fall-back to the default content type
            resolvedContentType = defaultContentType.ToString();
            resolvedContentTypeEncoding = defaultContentType.Encoding;
        }
コード例 #5
0
        public async Task Invoke(HttpContext httpContext)
        {
            // OnStarting handlers have to be set early during request processing,
            // even though they are used to create the response.

            // ----------------------
            // ASP.NET 4 - HttpContext.Response.Headers  
            // ASP.NET 4 - HttpContext.Response.Cookies  
            // 
            // Issue with all response headers is that they will not be sent after anything has been written to the
            // response body.
            // To solve this, use OnStarting to set a callback that will be called right before headers are sent.
            // Set the headers in that callback.
            //
            // Setting a cookie results in a Set-Cookie response header.
            // So use an OnStarting handler here as well.

            //>40
            httpContext.Response.OnStarting(SetHeaders, state: httpContext);
            httpContext.Response.OnStarting(SetCookies, state: httpContext);
            //<40

            // ==================================================================
            // Context

            // Unique request ID (no ASP.NET 4 counterpart)
            //>01
            string requestId = httpContext.TraceIdentifier;
            //<01

            // ASP.NET 4 - HttpContext.Items
            //>01b
            IDictionary<object, object> items = httpContext.Items;
            //<01b

            // ==================================================================
            // Request

            // ASP.NET 4 - HttpContext.Request.HttpMethod
            //>02
            string httpMethod = httpContext.Request.Method;
            //<02

            // ----------

            // ASP.NET 4 - HttpContext.Request.QueryString
            //>03
            IReadableStringCollection queryParameters = httpContext.Request.Query;

            // If no query parameter "key" used, values will have 0 items
            // If single value used for a key (...?key=v1), values will have 1 item ("v1")
            // If key has multiple values (...?key=v1&key=v2), values will have 2 items ("v1" and "v2")
            IList<string> values = queryParameters["key"];

            // If no query parameter "key" used, value will be ""
            // If single value used for a key (...?key=v1), value will be "v1"
            // If key has multiple values (...?key=v1&key=v2), value will be "v1,v2"
            string value = queryParameters["key"].ToString();
            //<03

            // ----------

            // ASP.NET 4 - HttpContext.Request.Url and HttpContext.Request.RawUrl
            //>04
            // using Microsoft.AspNet.Http.Extensions;
            var url = httpContext.Request.GetDisplayUrl();
            //<04

            // ASP.NET 4 - HttpContext.Request.IsSecureConnection
            //>05
            var isSecureConnection = httpContext.Request.IsHttps;
            //<05

            // ----------

            // ASP.NET 4 - HttpContext.Request.UserHostAddress
            //>06
            var userHostAddress = httpContext.Connection.RemoteIpAddress?.ToString();
            //<06

            // ----------

            // ASP.NET 4 - HttpContext.Request.Cookies 

            //>07
            IReadableStringCollection cookies = httpContext.Request.Cookies;
            string unknownCookieValue = cookies["unknownCookie"]; // will be null (no exception)
            string knownCookieValue = cookies["cookie1name"];     // will be actual value
            //<07

            // ----------

            // ASP.NET 4 - HttpContext.Request.RequestContext.RouteData
            // RouteData is not available in middleware in RC1. See
            // https://github.com/aspnet/Mvc/issues/3826
            // http://stackoverflow.com/questions/34083240/accessing-requestcontext-routedata-values-in-asp-net-5-vnext

            // ----------

            // ASP.NET 4 - HttpContext.Request.Headers
            //>08
            // using Microsoft.AspNet.Http.Headers;
            // using Microsoft.Net.Http.Headers;

            IHeaderDictionary headersDictionary = httpContext.Request.Headers;

            // GetTypedHeaders extension method provides strongly typed access to many headers
            var requestHeaders = httpContext.Request.GetTypedHeaders();
            CacheControlHeaderValue cacheControlHeaderValue = requestHeaders.CacheControl;

            // For unknown header, unknownheaderValues has zero items and unknownheaderValue is ""
            IList<string> unknownheaderValues = headersDictionary["unknownheader"];
            string unknownheaderValue = headersDictionary["unknownheader"].ToString();

            // For known header, knownheaderValues has 1 item and knownheaderValue is the value
            IList<string> knownheaderValues = headersDictionary[HeaderNames.AcceptLanguage];
            string knownheaderValue = headersDictionary[HeaderNames.AcceptLanguage].ToString();
            //<08

            // ----------

            // ASP.NET 4 - HttpContext.Request.UserAgent
            //>12
            string userAgent = headersDictionary[HeaderNames.UserAgent].ToString();
            //<12

            // ASP.NET 4 - HttpContext.Request.UrlReferrer
            //>13
            string urlReferrer = headersDictionary[HeaderNames.Referer].ToString();
            //<13

            // ASP.NET 4 - HttpContext.Request.ContentType 
            //>14
            // using Microsoft.Net.Http.Headers;

            MediaTypeHeaderValue mediaHeaderValue = requestHeaders.ContentType;
            string contentType = mediaHeaderValue?.MediaType;   // ex. application/x-www-form-urlencoded
            string contentMainType = mediaHeaderValue?.Type;    // ex. application
            string contentSubType = mediaHeaderValue?.SubType;  // ex. x-www-form-urlencoded

            System.Text.Encoding requestEncoding = mediaHeaderValue?.Encoding;
            //<14


            // ----------

            // ASP.NET 4 - HttpContext.Request.Form 
            //>15
            if (httpContext.Request.HasFormContentType)
            {
                IFormCollection form;

                form = httpContext.Request.Form; // sync
                // Or
                form = await httpContext.Request.ReadFormAsync(); // async

                string firstName = form["firstname"];
                string lastName = form["lastname"];
            }
            //<15
            // ----------
            // See 
            // http://stackoverflow.com/questions/31389781/read-body-twice-in-asp-net-5/

            // ASP.NET 4 - HttpContext.Request.InputStream
            // Unlike reading the form, reading the raw body is not from a buffer.
            // So you can only do this once per request.
            // 
            // If you need to read the body multiple times per request, see
            // http://stackoverflow.com/questions/31389781/read-body-twice-in-asp-net-5/

            //>16
            string inputBody;
            using (var reader = new System.IO.StreamReader(
                httpContext.Request.Body, System.Text.Encoding.UTF8))
            {
                inputBody = reader.ReadToEnd();
            }
            //<16

            // Use this middleware as a handler, so no call to 
            // await _next.Invoke(aspnet5HttpContext);

            // ==================================================================
            // Response

            // ASP.NET 4 - HttpContext.Response.Status  
            // ASP.NET 4 - HttpContext.Response.StatusDescription (obsolete, removed from HTTP/2) 
            //>30
            // using Microsoft.AspNet.Http;
            httpContext.Response.StatusCode = StatusCodes.Status200OK;
            //<30

            // ASP.NET 4 - HttpContext.Response.ContentEncoding and HttpContext.Response.ContentType  
            //>31
            // using Microsoft.Net.Http.Headers;
            var mediaType = new MediaTypeHeaderValue("application/json");
            mediaType.Encoding = System.Text.Encoding.UTF8;
            httpContext.Response.ContentType = mediaType.ToString();
            //<31

            // ASP.NET 4 - HttpContext.Response.ContentType only 
            //>32
            httpContext.Response.ContentType = "text/html";
            //<32

            // ----------------------
            // ASP.NET 4 - HttpContext.Response.Output  
            //
            //>33
            string responseContent = GetResponseContent();
            await httpContext.Response.WriteAsync(responseContent);
            //<33
        }
コード例 #6
0
 private static ActionContext GetActionContext(
     MediaTypeHeaderValue contentType,
     MemoryStream responseStream = null)
 {
     var request = new Mock<HttpRequest>();
     var headers = new HeaderDictionary();
     request.Setup(r => r.ContentType).Returns(contentType.ToString());
     request.SetupGet(r => r.Headers).Returns(headers);
     headers[HeaderNames.AcceptCharset] = contentType.Charset;
     var response = new Mock<HttpResponse>();
     response.SetupGet(f => f.Body).Returns(responseStream ?? new MemoryStream());
     var httpContext = new Mock<HttpContext>();
     httpContext.SetupGet(c => c.Request).Returns(request.Object);
     httpContext.SetupGet(c => c.Response).Returns(response.Object);
     return new ActionContext(httpContext.Object, routeData: null, actionDescriptor: null);
 }
コード例 #7
0
        public void ToString_UseDifferentMediaTypes_AllSerializedCorrectly()
        {
            var mediaType = new MediaTypeHeaderValue("text/plain");
            Assert.Equal("text/plain", mediaType.ToString());

            mediaType.Charset = "utf-8";
            Assert.Equal("text/plain; charset=utf-8", mediaType.ToString());

            mediaType.Parameters.Add(new NameValueHeaderValue("custom", "\"custom value\""));
            Assert.Equal("text/plain; charset=utf-8; custom=\"custom value\"", mediaType.ToString());

            mediaType.Charset = null;
            Assert.Equal("text/plain; custom=\"custom value\"", mediaType.ToString());
        }
コード例 #8
0
ファイル: ODataMediaTypes.cs プロジェクト: joshcomley/WebApi
 private static MediaTypeHeaderValue Clone(MediaTypeHeaderValue contentType)
 {
     return MediaTypeHeaderValue.Parse(contentType.ToString());
 }
コード例 #9
0
ファイル: FormatterMappings.cs プロジェクト: ymd1223/Mvc
        /// <summary>
        /// Sets mapping for the format to specified media type. 
        /// If the format already exists, the media type will be overwritten with the new value.
        /// </summary>
        /// <param name="format">The format value.</param>
        /// <param name="contentType">The media type for the format value.</param>
        public void SetMediaTypeMappingForFormat(string format, MediaTypeHeaderValue contentType)
        {
            if (format == null)
            {
                throw new ArgumentNullException(nameof(format));
            }

            if (contentType == null)
            {
                throw new ArgumentNullException(nameof(contentType));
            }

            ValidateContentType(contentType);
            format = RemovePeriodIfPresent(format);
            _map[format] = contentType.ToString();
        }