本文整理汇总了C#中System.Net.Http.Headers.MediaTypeHeaderValue类的典型用法代码示例。如果您正苦于以下问题:C# MediaTypeHeaderValue类的具体用法?C# MediaTypeHeaderValue怎么用?C# MediaTypeHeaderValue使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
MediaTypeHeaderValue类属于System.Net.Http.Headers命名空间,在下文中一共展示了MediaTypeHeaderValue类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: Execute
public override bool Execute()
{
HttpClient client = null;
try {
var jsonFormatter = new System.Net.Http.Formatting.JsonMediaTypeFormatter();
var mediaType = new MediaTypeHeaderValue("application/json");
var jsonSerializerSettings = new JsonSerializerSettings();
var requestMessage = new HttpRequestMessage<string>(
this.PostContent,
mediaType,
new MediaTypeFormatter[] { jsonFormatter });
client = new HttpClient();
HttpResponseMessage response = null;
System.Threading.Tasks.Task postTask = client.PostAsync(this.Url, requestMessage.Content).ContinueWith(respMessage => {
response = respMessage.Result;
});
System.Threading.Tasks.Task.WaitAll(new System.Threading.Tasks.Task[] { postTask });
response.EnsureSuccessStatusCode();
return true;
}
catch (Exception ex) {
string message = "Unable to post the message.";
throw new LoggerException(message,ex);
}
finally {
if (client != null) {
client.Dispose();
client = null;
}
}
}
示例2: SetSampleResponse
/// <summary>
/// Sets the sample request directly for the specified media type of the action.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration" />.</param>
/// <param name="sample">The sample response.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetSampleResponse(this HttpConfiguration config, object sample,
MediaTypeHeaderValue mediaType, string controllerName, string actionName) {
config.GetHelpPageSampleGenerator()
.ActionSamples.Add(
new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, new[] {"*"}),
sample);
}
示例3: SetSampleRequest
/// <summary>
/// Sets the sample request directly for the specified media type and action with parameters.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration" />.</param>
/// <param name="sample">The sample request.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType,
string controllerName, string actionName, params string[] parameterNames) {
config.GetHelpPageSampleGenerator()
.ActionSamples.Add(
new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, parameterNames),
sample);
}
示例4: Create
///<summary>
/// Creates a file parameter from an array of bytes.
///</summary>
///<param name="name">The parameter name to use in the request.</param>
///<param name="input">The input stream for the file's contents.</param>
///<param name="filename">The filename to use in the request.</param>
///<param name="contentType">The content type to use in the request.</param>
///<returns>The <see cref="FileParameter"/></returns>
public static FileParameter Create(string name, Stream input, string filename, MediaTypeHeaderValue contentType)
{
var temp = new MemoryStream();
input.CopyTo(temp);
var data = temp.ToArray();
return Create(name, data, filename, contentType);
}
示例5: SetDefaultContentHeaders
public override void SetDefaultContentHeaders(Type type, HttpContentHeaders headers, MediaTypeHeaderValue mediaType)
{
base.SetDefaultContentHeaders(type, headers, mediaType);
headers.ContentType = new MediaTypeHeaderValue(ApplicationJsonMediaType);
this.SerializerSettings.Formatting = Formatting.None;
this.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
}
示例6: SetDefaultContentHeaders
public override void SetDefaultContentHeaders(Type type, HttpContentHeaders headers, MediaTypeHeaderValue mediaType)
{
base.SetDefaultContentHeaders(type, headers, mediaType);
// Remove charset parameter. It must not be sent according to Json Api (http://jsonapi.org/format/#content-negotiation-servers)
headers.ContentType.CharSet = null;
}
示例7: MakeCachekey
protected virtual string MakeCachekey(HttpActionContext context, MediaTypeHeaderValue mediaType, bool excludeQueryString = false)
{
var controller = context.ControllerContext.ControllerDescriptor.ControllerName;
var action = context.ActionDescriptor.ActionName;
var key = context.Request.GetConfiguration().CacheOutputConfiguration().MakeBaseCachekey(controller, action);
var parametersCollections = context.ActionArguments.Where(x => x.Value != null).Select(x => x.Key + "=" + x.Value);
var parameters = "-"+string.Join("&", parametersCollections);
if (excludeQueryString)
{
parameters = string.Empty;
}
else
{
var callbackValue = GetJsonpCallback(context.Request);
if (!string.IsNullOrWhiteSpace(callbackValue))
{
var callback = "callback=" + callbackValue;
if (parameters.Contains("&" + callback)) parameters = parameters.Replace("&" + callback, string.Empty);
if (parameters.Contains(callback + "&")) parameters = parameters.Replace(callback + "&", string.Empty);
if (parameters.Contains("-" + callback)) parameters = parameters.Replace("-" + callback, string.Empty);
if (parameters.EndsWith("&")) parameters = parameters.TrimEnd('&');
}
}
if (parameters == "-") parameters = string.Empty;
var cachekey = string.Format("{0}{1}:{2}", key, parameters, mediaType.MediaType);
return cachekey;
}
示例8: FileRepresentationModel
public FileRepresentationModel(string filename, string fileExtension, byte[] contentAsByteArray, MediaTypeHeaderValue mediaTypeHeaderValue)
{
Filename = filename;
FileExtension = fileExtension;
ContentAsByteArray = contentAsByteArray;
MediaTypeHeaderValue = mediaTypeHeaderValue;
}
示例9: Create
public static MapRepresentation Create(IOidStrategy oidStrategy, HttpRequestMessage req, ContextFacade contextFacade, IList<ContextFacade> contexts, Format format, RestControlFlags flags, MediaTypeHeaderValue mt) {
var memberValues = contexts.Select(c => new OptionalProperty(c.Id, GetMap(oidStrategy, req, c, flags))).ToList();
IObjectFacade target = contexts.First().Target;
MapRepresentation mapRepresentation;
if (format == Format.Full) {
var tempProperties = new List<OptionalProperty>();
if (!string.IsNullOrEmpty(contextFacade?.Reason)) {
tempProperties.Add(new OptionalProperty(JsonPropertyNames.XRoInvalidReason, contextFacade.Reason));
}
var dt = new OptionalProperty(JsonPropertyNames.DomainType, target.Specification.DomainTypeName(oidStrategy));
tempProperties.Add(dt);
var members = new OptionalProperty(JsonPropertyNames.Members, Create(memberValues.ToArray()));
tempProperties.Add(members);
mapRepresentation = Create(tempProperties.ToArray());
}
else {
mapRepresentation = Create(memberValues.ToArray());
}
mapRepresentation.SetContentType(mt);
return mapRepresentation;
}
示例10: GetPerRequestFormatterInstance
public override MediaTypeFormatter GetPerRequestFormatterInstance(Type type, HttpRequestMessage request, MediaTypeHeaderValue mediaType)
{
if (_viewLocator == null || _viewParser == null)
{
var config = request.GetConfiguration();
if (config != null)
{
IViewLocator viewLocator = null;
IViewParser viewParser = null;
var resolver = config.DependencyResolver;
if (_viewLocator == null)
viewLocator = (IViewLocator) resolver.GetService(typeof (IViewLocator));
if (_viewParser == null)
viewParser = (IViewParser) resolver.GetService(typeof (IViewParser));
return new HtmlMediaTypeViewFormatter(_siteRootPath, viewLocator, viewParser);
}
}
return base.GetPerRequestFormatterInstance(type, request, mediaType);
}
示例11: GetPerRequestFormatterInstance
/// <summary>
/// Returns a specialized instance of the <see cref="T:System.Net.Http.Formatting.MediaTypeFormatter"/> that can format a response for the given parameters.
/// </summary>
/// <param name="type">The type to format.</param>
/// <param name="request">The request.</param>
/// <param name="mediaType">The media type.</param>
/// <returns>Returns <see cref="T:System.Net.Http.Formatting.MediaTypeFormatter"/>.</returns>
public override MediaTypeFormatter GetPerRequestFormatterInstance(Type type, HttpRequestMessage request, MediaTypeHeaderValue mediaType)
{
var parameters = request.RequestUri.ParseQueryString();
var prettify = false;
if (parameters[PrettifyParameterName] != null)
{
prettify = new[] { "yes", "1", "true" }.Contains(parameters[PrettifyParameterName], StringComparer.OrdinalIgnoreCase);
}
var fieldNamingStratgey = _fieldNamingStratgey;
if (parameters[FieldNamingStrategyParameterName] != null)
{
switch (parameters[FieldNamingStrategyParameterName])
{
case "none":
fieldNamingStratgey = new DefaultFieldNamingStrategy();
break;
case "dash":
fieldNamingStratgey = new DasherizedFieldNamingStrategy();
break;
case "snake":
fieldNamingStratgey = new SnakeCaseNamingStrategy();
break;
}
}
return new JsonApiMediaTypeFormatter(ContractResolver, fieldNamingStratgey, prettify);
}
示例12: Negotiate_ForRequestReturnsFirstMatchingFormatter
public void Negotiate_ForRequestReturnsFirstMatchingFormatter()
{
MediaTypeHeaderValue mediaType = new MediaTypeHeaderValue("application/myMediaType");
MediaTypeFormatter formatter1 = new MockMediaTypeFormatter()
{
CanWriteTypeCallback = (Type t) => false
};
MediaTypeFormatter formatter2 = new MockMediaTypeFormatter()
{
CanWriteTypeCallback = (Type t) => true
};
formatter2.SupportedMediaTypes.Add(mediaType);
MediaTypeFormatterCollection collection = new MediaTypeFormatterCollection(
new MediaTypeFormatter[]
{
formatter1,
formatter2
});
_request.Content = new StringContent("test", Encoding.Default, mediaType.MediaType);
var result = _negotiator.Negotiate(typeof(string), _request, collection);
Assert.Same(formatter2, result.Formatter);
Assert.MediaType.AreEqual(mediaType, result.MediaType, "Expected the formatter's media type to be returned.");
}
示例13: HelpPageSampleKey
/// <summary>
/// Creates a new <see cref="HelpPageSampleKey"/> based on media type, <see cref="SampleDirection"/>, controller name, action name and parameter names.
/// </summary>
/// <param name="mediaType">The media type.</param>
/// <param name="sampleDirection">The <see cref="SampleDirection"/>.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public HelpPageSampleKey(MediaTypeHeaderValue mediaType, SampleDirection sampleDirection, string controllerName, string actionName, IEnumerable<string> parameterNames)
{
if (mediaType == null)
{
throw new ArgumentNullException("mediaType");
}
if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection))
{
throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection));
}
if (controllerName == null)
{
throw new ArgumentNullException("controllerName");
}
if (actionName == null)
{
throw new ArgumentNullException("actionName");
}
if (parameterNames == null)
{
throw new ArgumentNullException("parameterNames");
}
ControllerName = controllerName;
ActionName = actionName;
MediaType = mediaType;
ParameterNames = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase);
SampleDirection = sampleDirection;
}
示例14: JsonSerializer
/// <summary>
/// Constructor which initializes this serializer
/// </summary>
public JsonSerializer()
{
ContentType = new MediaTypeHeaderValue("application/json")
{
CharSet = _encoding.WebName,
};
}
示例15: OpenSearchDescription
public OpenSearchDescription(MediaTypeHeaderValue contentType, Stream stream) : this(XDocument.Load(stream))
{
//if (contentType.MediaType != "application/opensearchdescription+xml")
//{
// throw new NotSupportedException("Do not understand " + contentType.MediaType + " as a search description language");
//}
}