本文整理汇总了C#中System.Net.Http.Headers.MediaTypeHeaderValue类的典型用法代码示例。如果您正苦于以下问题:C# MediaTypeHeaderValue类的具体用法?C# MediaTypeHeaderValue怎么用?C# MediaTypeHeaderValue使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
MediaTypeHeaderValue类属于System.Net.Http.Headers命名空间,在下文中一共展示了MediaTypeHeaderValue类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的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;
}
}
}
开发者ID:JustJenFelice,项目名称:sayed-samples,代码行数:35,代码来源:JsonHttpPost.cs
示例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);
}
开发者ID:sinch,项目名称:net-demo.sinch.com,代码行数:15,代码来源:HelpPageConfigurationExtensions.cs
示例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);
}
开发者ID:sinch,项目名称:net-demo.sinch.com,代码行数:16,代码来源:HelpPageConfigurationExtensions.cs
示例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);
}
开发者ID:changsunfung,项目名称:RestSharp.Portable,代码行数:15,代码来源:FileParameter.cs
示例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();
}
开发者ID:spptest,项目名称:Telerik,代码行数:7,代码来源:BrowserJsonFormatter.cs
示例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;
}
开发者ID:jayway,项目名称:khelg2015-3-team3,代码行数:7,代码来源:JsonApiMediaTypeFormatter.cs
示例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;
}
开发者ID:ZhouXiuming,项目名称:AspNetWebApi-OutputCache,代码行数:30,代码来源:BaseCacheAttribute.cs
示例8: FileRepresentationModel
public FileRepresentationModel(string filename, string fileExtension, byte[] contentAsByteArray, MediaTypeHeaderValue mediaTypeHeaderValue)
{
Filename = filename;
FileExtension = fileExtension;
ContentAsByteArray = contentAsByteArray;
MediaTypeHeaderValue = mediaTypeHeaderValue;
}
开发者ID:BerndVertommen,项目名称:EvaluationPlatform,代码行数:7,代码来源:FileRepresentationModel.cs
示例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;
}
开发者ID:NakedObjectsGroup,项目名称:NakedObjectsFramework,代码行数:27,代码来源:ArgumentsRepresentation.cs
示例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);
}
开发者ID:abhishekbhalani,项目名称:WebApiContrib.Formatting.Html,代码行数:25,代码来源:HtmlMediaTypeViewFormatter.cs
示例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);
}
开发者ID:cosullivan,项目名称:Hypermedia,代码行数:38,代码来源:JsonApiMediaTypeFormatter.cs
示例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.");
}
开发者ID:JokerMisfits,项目名称:linux-packaging-mono,代码行数:29,代码来源:DefaultContentNegotiatorTests.cs
示例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;
}
开发者ID:VisionSoftware,项目名称:assetManager,代码行数:36,代码来源:HelpPageSampleKey.cs
示例14: JsonSerializer
/// <summary>
/// Constructor which initializes this serializer
/// </summary>
public JsonSerializer()
{
ContentType = new MediaTypeHeaderValue("application/json")
{
CharSet = _encoding.WebName,
};
}
开发者ID:changsunfung,项目名称:RestSharp.Portable,代码行数:10,代码来源:JsonSerializer.cs
示例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");
//}
}
开发者ID:tavis-software,项目名称:Tavis.Link,代码行数:7,代码来源:OpenSearchDescription.cs
示例16: StringResponseWriter
public StringResponseWriter(string text, MediaTypeHeaderValue contentType)
{
VerifyArgument.IsNotNull("mediaType", contentType);
_text = text;
_contentType = contentType;
_enforceSizeCap = true;
}
开发者ID:Robin--,项目名称:Warewolf,代码行数:7,代码来源:StringResponseWriter.cs
示例17: ParsedMediaTypeHeaderValue
public ParsedMediaTypeHeaderValue(MediaTypeHeaderValue mediaType)
{
this.mediaType = mediaType;
string[] splitMediaType = mediaType.MediaType.Split(MediaTypeSubTypeDelimiter);
this.type = splitMediaType[0];
this.subType = splitMediaType[1];
}
开发者ID:JokerMisfits,项目名称:linux-packaging-mono,代码行数:7,代码来源:ParsedMediaTypeHeaderValue.cs
示例18: TypedJsonMediaTypeFormatter
public TypedJsonMediaTypeFormatter(Type resourceType, MediaTypeHeaderValue mediaType)
{
this.resourceType = resourceType;
this.SupportedMediaTypes.Clear();
this.SupportedMediaTypes.Add(mediaType);
}
开发者ID:MyGet,项目名称:webhooks-sign-package,代码行数:7,代码来源:TypedJsonMediaTypeFormatter.cs
示例19: OnActionExecuting
public override void OnActionExecuting(HttpActionContext ac)
{
if (ac != null)
{
if (_isCacheable(ac))
{
_cachekey = string.Join(":", new string[] { ac.Request.RequestUri.AbsolutePath, ac.Request.Headers.Accept.FirstOrDefault().ToString() });
if (WebApiCache.Contains(_cachekey))
{
var val = (string)WebApiCache.Get(_cachekey);
if (val != null)
{
var contenttype = (MediaTypeHeaderValue)WebApiCache.Get(_cachekey + ":response-ct");
if (contenttype == null)
contenttype = new MediaTypeHeaderValue(_cachekey.Split(':')[1]);
ac.Response = ac.Request.CreateResponse();
ac.Response.Content = new StringContent(val);
ac.Response.Content.Headers.ContentType = contenttype;
ac.Response.Headers.CacheControl = setClientCache();
return;
}
}
}
}
else
{
throw new ArgumentNullException("actionContext");
}
}
开发者ID:AlexZeitler,项目名称:HypermediaApiSite,代码行数:33,代码来源:WebApiOutputCacheAttribute.cs
示例20: Constructor
public void Constructor(string queryStringParameterName, string queryStringParameterValue, MediaTypeHeaderValue mediaType)
{
QueryStringMapping mapping = new QueryStringMapping(queryStringParameterName, queryStringParameterValue, mediaType);
Assert.Equal(queryStringParameterName, mapping.QueryStringParameterName);
Assert.Equal(queryStringParameterValue, mapping.QueryStringParameterValue);
Assert.MediaType.AreEqual(mediaType, mapping.MediaType, "MediaType failed to set.");
}
开发者ID:reza899,项目名称:aspnetwebstack,代码行数:7,代码来源:QueryStringMappingTests.cs
注:本文中的System.Net.Http.Headers.MediaTypeHeaderValue类示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论