当前位置: 首页>>代码示例>>C#>>正文


C# ObjectContent类代码示例

本文整理汇总了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;
        }
开发者ID:iansrobinson,项目名称:Restbucks,代码行数:7,代码来源:ApplicationStateVariablesFormDataStrategy.cs

示例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;
        }
开发者ID:ChrisMissal,项目名称:WcfWebApiContrib,代码行数:7,代码来源:ObjectContentTests.cs

示例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 };
 }
开发者ID:fgNv,项目名称:SoccerFanTest,代码行数:7,代码来源:ExceptionHandling.cs

示例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();
        }
开发者ID:gudicao,项目名称:WebApiStu,代码行数:35,代码来源:Program.cs

示例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};
        }
开发者ID:iansrobinson,项目名称:Restbucks,代码行数:7,代码来源:DummyResponse.cs

示例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);
        }
开发者ID:wis3guy,项目名称:Nfield-SDK,代码行数:25,代码来源:HttpResponseMessageExtensionsTests.cs

示例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;
                    }
                }
            }
        }
开发者ID:ahaydara,项目名称:html5_learning,代码行数:25,代码来源:ModelStateFilter.cs

示例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);
            }
        }
开发者ID:sanghyukp,项目名称:AngularJSWebAPI2,代码行数:33,代码来源:UnitTest1.cs

示例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);
        }
开发者ID:diouf,项目名称:apress-recipes-webapi,代码行数:7,代码来源:ProtoBufFormatterTest.cs

示例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;
   }
 }
开发者ID:mkeeton,项目名称:BasicMVC,代码行数:33,代码来源:LoginProperties.cs

示例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);
         }
     }
 }
开发者ID:elefantstudio-se,项目名称:ElefantStudio-Prototyp-Exempel,代码行数:35,代码来源:ObjectLayerContent.cs

示例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);
                }
            }
        }
开发者ID:caironm,项目名称:bob-api-client-example,代码行数:59,代码来源:Program.cs

示例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);
        }
开发者ID:JokerMisfits,项目名称:linux-packaging-mono,代码行数:8,代码来源:ObjectContentOfTTests.cs

示例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);
        }
开发者ID:sanyaade-mobiledev,项目名称:aspnetwebstack-1,代码行数:8,代码来源:HttpContentExtensionsTest.cs

示例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;
 }
开发者ID:asdlvs,项目名称:SomethingRest,代码行数:8,代码来源:ObjectContentWriter.cs


注:本文中的ObjectContent类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。