本文整理汇总了C#中ObjectContent类的典型用法代码示例。如果您正苦于以下问题:C# ObjectContent类的具体用法?C# ObjectContent怎么用?C# ObjectContent使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
ObjectContent类属于命名空间,在下文中一共展示了ObjectContent类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: CreateFormData
public HttpContent CreateFormData(HttpResponseMessage previousResponse, ApplicationStateVariables stateVariables, IClientCapabilities clientCapabilities)
{
var content = new ObjectContent(typeof(object), stateVariables.Get<object>(key), new[] { clientCapabilities.GetMediaTypeFormatter(contentType) });
content.Headers.ContentType = contentType;
return content;
}
示例2: GetFoo
public HttpResponseMessage GetFoo()
{
var content = new ObjectContent<string>("woof", "text/plain", new[] { new PlainTextFormatter() }); // including formatters here doesn't actually help!
var response = new HttpResponseMessage { Content = content };
return response;
}
示例3: BuildContent
private static HttpResponseMessage BuildContent(IEnumerable<string> messages)
{
var exceptionMessage = new ExceptionResponse { Messages = messages };
var formatter = new JsonMediaTypeFormatter();
var content = new ObjectContent<ExceptionResponse>(exceptionMessage, formatter, "application/json");
return new HttpResponseMessage { Content = content };
}
示例4: Main
static void Main(string[] args)
{
System.Threading.Thread.Sleep(100);
Console.Clear();
Console.WriteLine("**************************开始执行获取API***********************************");
HttpClient client = new HttpClient();
//Get All Product 获取所有
HttpResponseMessage responseGetAll = client.GetAsync(url + "api/Products").Result;
string GetAllProducts = responseGetAll.Content.ReadAsStringAsync().Result;
Console.WriteLine("GetAllProducts方法:" + GetAllProducts);
//Get Product根据ID获取
HttpResponseMessage responseGetID = client.GetAsync(url + "api/Products/1").Result;
string GetProduct = responseGetID.Content.ReadAsStringAsync().Result;
Console.WriteLine("GetProduct方法:" + GetProduct);
//Delete Product 根据ID删除
HttpResponseMessage responseDeleteID = client.DeleteAsync(url + "api/Products/1").Result;
// string DeleteProduct = responseDeleteID.Content.ReadAsStringAsync().Result;
Console.WriteLine("DeleteProduct方法:" );
//HttpContent abstract 类
//Post Product 添加Product对象
var model = new Product { Id = 3, Name = "Hammer", Category = "Hardware", Price = 16.99M };
HttpContent content = new ObjectContent(typeof(Product), model, new JsonMediaTypeFormatter());
client.PostAsync(url + "api/Products/", content);
//Put Product 修改Product
client.PutAsync(url + "api/Products/", content);
Console.ReadKey();
}
示例5: CreateResponse
public static HttpResponseMessage CreateResponse()
{
var content = new ObjectContent<ExampleEntityBody>(EntityBody, new[] {ExampleMediaType.Instance});
content.Headers.ContentType = ExampleMediaType.ContentType;
return new HttpResponseMessage {Content = content};
}
示例6: HttpResponseMessage
public void TestValidateResponse_ServerReturnsNfieldErrorCodeAndMessage_ThrowsNfieldErrorExceptionWithErrorCodeAndMessage()
{
// Arrange
const HttpStatusCode httpStatusCode = HttpStatusCode.NotFound;
const NfieldErrorCode nfieldErrorCode = NfieldErrorCode.ArgumentIsNull;
const string message = "Message #1";
var serverResponse = new HttpResponseMessage(httpStatusCode);
var httpErrorMock = new Dictionary<string, object>()
{
{ "NfieldErrorCode", nfieldErrorCode },
{ "Message", message }
};
HttpContent content = new ObjectContent<Dictionary<string, object>>(httpErrorMock, new JsonMediaTypeFormatter());
serverResponse.Content = content;
// Act
Assert.ThrowsDelegate actCode = () => serverResponse.ValidateResponse();
// Assert
var ex = Assert.Throws<NfieldErrorException>(actCode);
Assert.Equal(ex.HttpStatusCode, httpStatusCode);
Assert.Equal(ex.NfieldErrorCode, nfieldErrorCode);
Assert.Equal(ex.Message, message);
}
示例7: OnActionExecuted
public override void OnActionExecuted(System.Web.Http.Filters.HttpActionExecutedContext actionExecutedContext)
{
if (!actionExecutedContext.Response.IsSuccessStatusCode)
{
var contentObject = actionExecutedContext.Response.Content as ObjectContent;
if (contentObject != null)
{
var modelState = contentObject.Value as ModelStateDictionary;
if (modelState != null)
{
var errors =
(from item in modelState
from value in item.Value.Errors
select value.ErrorMessage).ToArray();
var configuration = actionExecutedContext.Request.GetConfiguration();
var contentNegotiator = configuration.Services.GetContentNegotiator();
var formatters = configuration.Formatters;
var result = contentNegotiator.Negotiate(errors.GetType(), actionExecutedContext.Request, formatters);
var content = new ObjectContent(errors.GetType(), errors, result.Formatter, result.MediaType.MediaType);
actionExecutedContext.Response.Content = content;
}
}
}
}
示例8: TestMethod1
public void TestMethod1()
{
try
{
Task serviceTask = new Task();
serviceTask.TaskId = 1;
serviceTask.Subject = "Test Task";
serviceTask.StartDate = DateTime.Now;
serviceTask.DueDate = null;
serviceTask.CompletedDate = DateTime.Now;
serviceTask.Status = new Status
{
StatusId = 3,
Name = "Completed",
Ordinal = 2
};
serviceTask.Links = new System.Collections.Generic.List<Link>();
serviceTask.Assignees = new System.Collections.Generic.List<User>();
serviceTask.SetShouldSerializeAssignees(true);
var formatter = new JsonMediaTypeFormatter();
var content = new ObjectContent<Task>(serviceTask, formatter);
var reuslt = content.ReadAsStringAsync().Result;
}
catch(Exception ex)
{
Assert.Fail(ex.Message);
}
}
示例9: WhenInvokedContentHeadersShouldBeSetCorrectly
public void WhenInvokedContentHeadersShouldBeSetCorrectly()
{
var item = new Item { Id = 1, Name = "Filip" };
var content = new ObjectContent<Item>(item, new ProtoBufFormatter());
Assert.Equal("application/x-protobuf", content.Headers.ContentType.MediaType);
}
示例10: SetLoginPropertyValue
public static async Task<bool> SetLoginPropertyValue(string propertyName, string propertyValue)
{
bool _Response;
try
{
using (var client = new HttpClient())
{
client.BaseAddress = new Uri(System.Web.Configuration.WebConfigurationManager.AppSettings["SSOURL"]);
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
// New code:
LoginPropertyModel _data = new LoginPropertyModel();
_data.SessionToken = new Guid(Repositories.CookieRepository.GetCookieValue("SessionID", Guid.NewGuid().ToString()));
_data.PropertyName = propertyName;
_data.PropertyValue = propertyValue;
var content = new ObjectContent<LoginPropertyModel>(_data, new JsonMediaTypeFormatter());
HttpResponseMessage response = await client.PostAsync("API/LoginProperty",content);
if (response.IsSuccessStatusCode)
{
_Response = response.Content.ReadAsAsync<bool>().Result;
return _Response;
}
else
{
return false;
}
}
}
catch (Exception)
{
return false;
}
}
示例11: ObjectLayerContent
public ObjectLayerContent(XmlNode node, LevelContent level)
: base(node)
{
// Construct xpath query for all available objects.
string[] objectNames = (from x in level.Project.Objects select x.Name).ToArray<string>();
string xpath = string.Join("|", objectNames);
foreach (XmlNode objectNode in node.SelectNodes(xpath))
{
ObjectTemplateContent objTemplate = level.Project.Objects.First<ObjectTemplateContent>((x) => { return x.Name.Equals(objectNode.Name); });
if (objTemplate != null)
{
ObjectContent obj = new ObjectContent(objectNode, objTemplate);
foreach (ValueTemplateContent valueContent in objTemplate.Values)
{
XmlAttribute attribute = null;
if ((attribute = objectNode.Attributes[valueContent.Name]) != null)
{
if (valueContent is BooleanValueTemplateContent)
obj.Values.Add(new BooleanValueContent(valueContent.Name, bool.Parse(attribute.Value)));
else if (valueContent is IntegerValueTemplateContent)
obj.Values.Add(new IntegerValueContent(valueContent.Name,
int.Parse(attribute.Value, CultureInfo.InvariantCulture)));
else if (valueContent is NumberValueTemplateContent)
obj.Values.Add(new NumberValueContent(valueContent.Name,
float.Parse(attribute.Value, CultureInfo.InvariantCulture)));
else if (valueContent is StringValueTemplateContent)
obj.Values.Add(new StringValueContent(valueContent.Name, attribute.Value));
}
}
foreach (XmlNode nodeNode in objectNode.SelectNodes("node"))
obj.Nodes.Add(new NodeContent(nodeNode));
this.Objects.Add(obj);
}
}
}
示例12: RunAsync
static async Task RunAsync(string portfolio)
{
using (var client = new HttpClient())
{
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
var account = new CompletionUpdateModel
{
PortfolioID = portfolio,
MMDate = "2013/10/15",
Cluster1 = "AC",
Cluster2 = "AB",
ResultURL = "http://cc/" + portfolio,
PhoneNumber = "5556667777",
TerminosCC = "1"
};
var BOB_SECRET_KEY = "VY72IUVROA6LTYHK";
var totp = new OTPNet.TOTP(BOB_SECRET_KEY, 90);
var jsonFormatter = new JsonMediaTypeFormatter();
var content = new ObjectContent<CompletionUpdateModel>(account, jsonFormatter);
var url = "https://1-dot-dazzling-rex-760.appspot.com/_ah/api/bob/v1/bob/completionupdate";
var requestUri = new Uri(url);
var request = new HttpRequestMessage
{
RequestUri = requestUri,
Method = HttpMethod.Post,
Content = content
};
request.Content.Headers.ContentType = new MediaTypeWithQualityHeaderValue("application/json");
request.Headers.Add("BobUniversity", "cc");
var code = totp.now();
request.Headers.Add("BobToken", code.ToString());
var response = client.SendAsync(request).Result;
Console.WriteLine("HTTP status code: {0}", response.StatusCode);
if (response.IsSuccessStatusCode)
{
var jsonString = await response.Content.ReadAsStringAsync();
var caresponse = JsonConvert.DeserializeObject<CompletionUpdateResponseModel>(jsonString);
Console.WriteLine("Codigo: {0}", caresponse.Codigo);
Console.WriteLine("Mensaje: {0}", caresponse.Mensaje);
}
}
}
示例13: Constructor_SetsFormatterProperty
public void Constructor_SetsFormatterProperty()
{
var formatter = new Mock<MediaTypeFormatter>().Object;
var content = new ObjectContent<string>(null, formatter, mediaType: null);
Assert.Same(formatter, content.Formatter);
}
示例14: ReadAsAsyncOfT_WhenContentIsObjectContent_GoesThroughSerializationCycleToConvertTypes
public void ReadAsAsyncOfT_WhenContentIsObjectContent_GoesThroughSerializationCycleToConvertTypes()
{
var content = new ObjectContent<int[]>(new int[] { 10, 20, 30, 40 }, new JsonMediaTypeFormatter());
byte[] result = content.ReadAsAsync<byte[]>().Result;
Assert.Equal(new byte[] { 10, 20, 30, 40 }, result);
}
示例15: Create
public override HttpContent Create(object item)
{
var type = item.GetType();
MediaTypeFormatter formatter = DefineFormatter(this.Accept, type);
var content = new ObjectContent(type, item, formatter);
content.Headers.ContentType = MediaTypeHeaderValue.Parse(this.ContentType);
return content;
}