本文整理汇总了C#中Microsoft.Net.Http.Headers.MediaTypeHeaderValue.ToString方法的典型用法代码示例。如果您正苦于以下问题:C# MediaTypeHeaderValue.ToString方法的具体用法?C# MediaTypeHeaderValue.ToString怎么用?C# MediaTypeHeaderValue.ToString使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类Microsoft.Net.Http.Headers.MediaTypeHeaderValue
的用法示例。
在下文中一共展示了MediaTypeHeaderValue.ToString方法的8个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: ReturnScript
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);
}
示例2: ExecuteAsync
/// <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);
}
}
示例3: ResolveContentTypeAndEncoding
/// <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;
}
示例4: Invoke
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
//.........这里部分代码省略.........
示例5: GetActionContext
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);
}
示例6: ToString_UseDifferentMediaTypes_AllSerializedCorrectly
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());
}
示例7: Clone
private static MediaTypeHeaderValue Clone(MediaTypeHeaderValue contentType)
{
return MediaTypeHeaderValue.Parse(contentType.ToString());
}
示例8: SetMediaTypeMappingForFormat
/// <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();
}