本文整理汇总了C#中System.Net.Http.Headers.MediaTypeWithQualityHeaderValue类的典型用法代码示例。如果您正苦于以下问题:C# MediaTypeWithQualityHeaderValue类的具体用法?C# MediaTypeWithQualityHeaderValue怎么用?C# MediaTypeWithQualityHeaderValue使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
MediaTypeWithQualityHeaderValue类属于System.Net.Http.Headers命名空间,在下文中一共展示了MediaTypeWithQualityHeaderValue类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: CreateItems
protected async Task<Boolean> CreateItems(string token)
{
var client = new HttpClient();
client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", token);
var mediaType = new MediaTypeWithQualityHeaderValue ("application/json");
mediaType.Parameters.Add (new NameValueHeaderValue ("odata", "verbose"));
client.DefaultRequestHeaders.Accept.Add (mediaType);
var itemToCreateTitle = "Item created on: " + DateTime.Now.ToString("dd/MM HH:mm");
var body = "{\"__metadata\":{\"type\":\"SP.Data.TasksByAndroidListItem\"},\"Title\":\"" + itemToCreateTitle + "\",\"Status\": \"Not Started\"}";
var contents = new StringContent (body);
contents.Headers.ContentType = MediaTypeHeaderValue.Parse( "application/json;odata=verbose");
try {
var postResult = await client.PostAsync ("https://mayurtendulkar.sharepoint.com/_api/web/lists/GetByTitle('TasksByAndroid')/items", contents);
var result = postResult.EnsureSuccessStatusCode();
if(result.IsSuccessStatusCode)
Toast.MakeText (this, "List item created successfully!", ToastLength.Long).Show();
return true;
} catch (Exception ex) {
var msg = "Unable to create list item. " + ex.Message;
Toast.MakeText (this, msg, ToastLength.Long).Show();
return false;
}
}
示例2: TryParse_SetOfValidValueStringsForMediaTypeWithQuality_ParsedCorrectly
public void TryParse_SetOfValidValueStringsForMediaTypeWithQuality_ParsedCorrectly()
{
MediaTypeWithQualityHeaderValue expected = new MediaTypeWithQualityHeaderValue("text/plain");
CheckValidParsedValue("\r\n text/plain ", 0, expected, 15, true);
CheckValidParsedValue("text/plain", 0, expected, 10, true);
CheckValidParsedValue("\r\n text/plain , next/mediatype", 0, expected, 17, true);
CheckValidParsedValue("text/plain, next/mediatype", 0, expected, 12, true);
CheckValidParsedValue(" ", 0, null, 2, true);
CheckValidParsedValue("", 0, null, 0, true);
CheckValidParsedValue(null, 0, null, 0, true);
CheckValidParsedValue(" ,,", 0, null, 4, true);
// Note that even if the whole string is invalid, the first media-type value is valid. When the parser
// gets called again using the result-index (13), then it fails: I.e. we have 1 valid media-type and an
// invalid one.
CheckValidParsedValue("text/plain , invalid", 0, expected, 13, true);
// We don't have to test all possible input strings, since most of the pieces are handled by other parsers.
// The purpose of this test is to verify that these other parsers are combined correctly to build a
// media-type parser.
expected.CharSet = "utf-8";
CheckValidParsedValue("\r\n text / plain ; charset = utf-8 ", 0, expected, 40, true);
CheckValidParsedValue(" text/plain;charset=utf-8", 2, expected, 26, true);
CheckValidParsedValue("\r\n text / plain ; charset = utf-8 , next/mediatype", 0, expected, 43, true);
CheckValidParsedValue(" text/plain;charset=utf-8, next/mediatype", 2, expected, 28, true);
}
示例3: SendAsync
private async Task<JToken> SendAsync(HttpMethod method, string endpoint, bool acceptJson = true, HttpContent content = null)
{
var requestUrl = new Uri(_serverUrl, endpoint);
var request = new HttpRequestMessage(method, requestUrl);
if (acceptJson)
{
var acceptJsonHeader = new MediaTypeWithQualityHeaderValue("application/json");
request.Headers.Accept.Add(acceptJsonHeader);
}
if (content != null)
{
request.Content = content;
}
var response = await _httpClient.SendAsync(request);
response.EnsureSuccessStatusCode();
if (acceptJson)
{
var json = await response.Content.ReadAsStringAsync();
return JsonConvert.DeserializeObject<JToken>(json);
}
return null;
}
示例4: When_POST_request_headers_are_preserved
public async Task When_POST_request_headers_are_preserved()
{
var client = new HttpClient();
var request = new HttpRequestMessage(HttpMethod.Post, _baseAddress + "Test");
var acceptHeaders = new MediaTypeWithQualityHeaderValue[]
{
new MediaTypeWithQualityHeaderValue("text/plain"),
new MediaTypeWithQualityHeaderValue("application/xml", 0.13)
};
foreach (var h in acceptHeaders) { request.Headers.Accept.Add(h); }
request.Headers.Add("X-CustomHeader", "value1");
request.Headers.Add("X-CustomHeader", "value2");
request.Content = new StringContent("some content");
request.Content.Headers.ContentLanguage.Add("en-gb");
request.Content.Headers.ContentLanguage.Add("en-us");
var rt = client.SendAsync(request);
TestController.OnPost(req =>
{
foreach (var h in acceptHeaders)
{
Assert.True(req.Headers.Accept.Contains(h));
}
var customHeader = req.Headers.First(kvp => kvp.Key == "X-CustomHeader");
Assert.NotNull(customHeader);
Assert.True(customHeader.Value.Any(s => s.Contains("value1")));
Assert.True(customHeader.Value.Any(s => s.Contains("value2")));
Assert.True(req.Content.Headers.ContentLanguage.Contains("en-gb"));
Assert.True(req.Content.Headers.ContentLanguage.Contains("en-us"));
return new HttpResponseMessage();
});
var response = await rt;
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
}
示例5: Compare_Returns_0_For_MediaTypeHeaderValues_With_Same_Q_Value
public void Compare_Returns_0_For_MediaTypeHeaderValues_With_Same_Q_Value()
{
MediaTypeHeaderValueComparer comparer = MediaTypeHeaderValueComparer.Comparer;
MediaTypeWithQualityHeaderValue mediaType1 = new MediaTypeWithQualityHeaderValue("text/xml", 0.5);
MediaTypeWithQualityHeaderValue mediaType2 = new MediaTypeWithQualityHeaderValue("text/xml", 0.50);
Assert.AreEqual(0, comparer.Compare(mediaType1, mediaType2), "Compare should have returned '0'.");
mediaType1 = new MediaTypeWithQualityHeaderValue("text/xml", .7);
mediaType2 = new MediaTypeWithQualityHeaderValue("application/xml", .7);
Assert.AreEqual(0, comparer.Compare(mediaType1, mediaType2), "Compare should have returned '0'.");
mediaType1 = new MediaTypeWithQualityHeaderValue("text/xml");
mediaType2 = new MediaTypeWithQualityHeaderValue("text/xml");
Assert.AreEqual(0, comparer.Compare(mediaType1, mediaType2), "Compare should have returned '0'.");
mediaType1 = new MediaTypeWithQualityHeaderValue("text/xml");
mediaType2 = new MediaTypeWithQualityHeaderValue("text/plain");
Assert.AreEqual(0, comparer.Compare(mediaType1, mediaType2), "Compare should have returned '0'.");
mediaType1 = new MediaTypeWithQualityHeaderValue("text/*", 0.3);
mediaType2 = new MediaTypeWithQualityHeaderValue("text/*", .3);
Assert.AreEqual(0, comparer.Compare(mediaType1, mediaType2), "Compare should have returned '0'.");
mediaType1 = new MediaTypeWithQualityHeaderValue("*/*");
mediaType2 = new MediaTypeWithQualityHeaderValue("*/*");
Assert.AreEqual(0, comparer.Compare(mediaType1, mediaType2), "Compare should have returned '0'.");
mediaType1 = new MediaTypeWithQualityHeaderValue("text/*", .1);
mediaType2 = new MediaTypeWithQualityHeaderValue("application/xml", .1);
Assert.AreEqual(0, comparer.Compare(mediaType1, mediaType2), "Compare should have returned '0'.");
}
示例6: Clone_Call_CloneFieldsMatchSourceFields
public void Clone_Call_CloneFieldsMatchSourceFields()
{
// This test just verifies that MediaTypeWithQualityHeaderValue calls the correct base implementation.
MediaTypeWithQualityHeaderValue source = new MediaTypeWithQualityHeaderValue("application/xml");
MediaTypeWithQualityHeaderValue clone = (MediaTypeWithQualityHeaderValue)((ICloneable)source).Clone();
Assert.Equal(source.MediaType, clone.MediaType);
Assert.Equal(0, clone.Parameters.Count);
source.CharSet = "utf-8";
source.Quality = 0.1;
clone = (MediaTypeWithQualityHeaderValue)((ICloneable)source).Clone();
Assert.Equal(source.MediaType, clone.MediaType);
Assert.Equal("utf-8", clone.CharSet);
Assert.Equal(0.1, clone.Quality);
Assert.Equal(2, clone.Parameters.Count);
source.Parameters.Add(new NameValueHeaderValue("custom", "customValue"));
clone = (MediaTypeWithQualityHeaderValue)((ICloneable)source).Clone();
Assert.Equal(source.MediaType, clone.MediaType);
Assert.Equal("utf-8", clone.CharSet);
Assert.Equal(0.1, clone.Quality);
Assert.Equal(3, clone.Parameters.Count);
Assert.Equal("custom", clone.Parameters.ElementAt(2).Name);
Assert.Equal("customValue", clone.Parameters.ElementAt(2).Value);
}
示例7: RenameAsset
public async void RenameAsset(IAsset asset, string newName)
{
// Create the request
var client = new HttpClient();
var resource = string.Format("https://wamsbluclus001rest-hs.cloudapp.net/API/Assets('{0}')", asset.Id);
var request = new HttpRequestMessage(new HttpMethod("MERGE"), resource);
// Set the request content
var content = string.Format("{{ 'Name' : '{0}' }}", newName);
var stringContent = new StringContent(content, Encoding.UTF8, "application/json");
var oDataParameter = new NameValueHeaderValue("odata", "verbose");
stringContent.Headers.ContentType.Parameters.Add(oDataParameter);
request.Content = stringContent;
// Set the request headers
var jsonAccessToken = await this.GetAccessToken();
string accessToken = JsonConvert.DeserializeObject<dynamic>(jsonAccessToken).access_token.Value;
request.Headers.Add("Authorization", "Bearer " + accessToken);
request.Headers.Add("DataServiceVersion", "3.0");
request.Headers.Add("MaxDataServiceVersion", "3.0");
request.Headers.Add("x-ms-version", "1.0");
request.Headers.Host = "wamsbluclus001rest-hs.cloudapp.net";
var mediaType = new MediaTypeWithQualityHeaderValue("application/json");
mediaType.Parameters.Add(oDataParameter);
client.DefaultRequestHeaders.Accept.Add(mediaType);
// Make the request
var response = await client.SendAsync(request);
response.EnsureSuccessStatusCode();
}
示例8: Ctor_AddNameAndQuality_QualityParameterAdded
public void Ctor_AddNameAndQuality_QualityParameterAdded()
{
MediaTypeWithQualityHeaderValue mediaType = new MediaTypeWithQualityHeaderValue("application/xml", 0.08);
Assert.Equal(0.08, mediaType.Quality);
Assert.Equal("application/xml", mediaType.MediaType);
Assert.Equal(1, mediaType.Parameters.Count);
}
示例9: GetUsers
public static List<UserModel> GetUsers(string accessToken)
{
List<UserModel> users = new List<UserModel>();
MediaTypeWithQualityHeaderValue Json = new MediaTypeWithQualityHeaderValue("application/json");
using (var client = new HttpClient())
{
using (var request = new HttpRequestMessage(HttpMethod.Get, @"https://graph.microsoft.com/v1.0/users"))
{
request.Headers.Accept.Add(Json);
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
using (var response = client.SendAsync(request).Result)
{
if (response.StatusCode == HttpStatusCode.OK)
{
var json = JObject.Parse(response.Content.ReadAsStringAsync().Result);
foreach (JToken user in json.SelectToken("value").Children())
{
users.Add(new UserModel(user));
}
}
}
}
}
return users;
}
示例10: SelectsSuperItemBasedOnParameter_5LMT
public void SelectsSuperItemBasedOnParameter_5LMT()
{
// arrange
var configuration = new HttpConfiguration();
configuration.Services.Replace(typeof(IHttpActionSelector), new MediaTypeBasedActionSelector());
configuration.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
configuration.AddFiveLevelsOfMediaType();
var server = new InMemoryServer(configuration);
var client = new HttpClient(server);
var request = new HttpRequestMessage(HttpMethod.Get, "http://lhasa/api/Item/1");
var headerValue = new MediaTypeWithQualityHeaderValue("application/json");
headerValue.Parameters.Add(new NameValueHeaderValue("domain-model", "SuperItem"));
request.Headers.Accept.Add(headerValue);
// act
var response = client.SendAsync(request).Result;
var content = response.Content.ReadAsStringAsync().Result;
var mediaType = response.Content.Headers.ContentType.ExtractFiveLevelsOfMediaType();
// assert
Assert.Equal("SuperItem", mediaType.DomainModel);
}
示例11: ExtractApiVersion
private int ExtractApiVersion(MediaTypeWithQualityHeaderValue header)
{
var apiVersionIndex = header.MediaType.IndexOf("api.v", StringComparison.InvariantCultureIgnoreCase) + 5;
var formatSpecificationIndex = header.MediaType.IndexOf("+", StringComparison.InvariantCultureIgnoreCase);
var versionTextLength = formatSpecificationIndex - apiVersionIndex;
return int.Parse(header.MediaType.Substring(apiVersionIndex, versionTextLength));
}
示例12: ConstructRequest
// Private helpers
private static HttpRequestMessage ConstructRequest(
HttpMethod httpMethod, string uri,
MediaTypeWithQualityHeaderValue mediaType) {
return ConstructRequest(
httpMethod,
uri,
new[] { mediaType });
}
示例13: TryParse
public static bool TryParse (string input, out MediaTypeWithQualityHeaderValue parsedValue)
{
var lexer = new Lexer (input);
Token token;
if (TryParseElement (lexer, out parsedValue, out token) && token == Token.Type.End)
return true;
parsedValue = null;
return false;
}
示例14: Program
static Program()
{
_formatters = new List<MediaTypeFormatter> { new JsonMediaTypeFormatter
{
SerializerSettings = new JsonSerializerSettings
{
TypeNameHandling = TypeNameHandling.Objects
}
}};
_mediaTypeJson = new MediaTypeWithQualityHeaderValue("application/json");
}
示例15: CreateAcceptHeader
public void CreateAcceptHeader()
{
var expected = new MediaTypeWithQualityHeaderValue("application/json");
var sut = new SutBuilder<RequestHeaderFactory>().Build();
using (var client = new HttpClient())
{
sut.SetHeaders(client.DefaultRequestHeaders);
Assert.AreEqual(client.DefaultRequestHeaders.Accept.First(), expected);
}
}