c# - Web.Api 接受参数形式的值

标签 c# .net asp.net-web-api

我正在使用 web.api 2.2,客户端以这种方式发送数据:

data={"kind": "Conversation", "tags": [], "items": [{"body": "hi there", "timestamp": "1445958749.284379", "kind": "MessageToOperator", "nickname": "United Kingdom (Rickmansworth) #5043", "visitor_nickname": "United Kingdom (Rickmansworth) #5043"}, {"body": "my name is amel and i am testing olark", "timestamp": "1445958753.320339", "kind": "MessageToOperator", "nickname": "United Kingdom (Rickmansworth) #5043", "visitor_nickname": "United Kingdom (Rickmansworth) #5043"}, {"body": "hi amel i am jessica", "timestamp": "1445958763.486881", "kind": "MessageToVisitor", "nickname": "Jessica Wood ", "operatorId": "744399"}, {"body": "ok im back", "timestamp": "1445959002.452643", "kind": "MessageToOperator", "nickname": "United Kingdom (Rickmansworth) #5043", "visitor_nickname": "United Kingdom (Rickmansworth) #5043"}, {"body": "hello there", "timestamp": "1445959059.642775", "kind": "MessageToVisitor", "nickname": "Jessica Wood ", "operatorId": "744399"}, {"body": "i ma here", "timestamp": "1445959066.829973", "kind": "MessageToOperator", "nickname": "United Kingdom (Rickmansworth) #5043", "visitor_nickname": "United Kingdom (Rickmansworth) #5043"}, {"body": "test", "timestamp": "1445959885.173931", "kind": "MessageToOperator", "nickname": "United Kingdom (Rickmansworth) #5043", "visitor_nickname": "United Kingdom (Rickmansworth) #5043"}, {"body": "hi there", "timestamp": "1445959894.323173", "kind": "MessageToVisitor", "nickname": "Jessica Wood ", "operatorId": "744399"}, {"body": "how are you doing", "timestamp": "1445959900.186131", "kind": "MessageToVisitor", "nickname": "Jessica Wood ", "operatorId": "744399"}, {"body": "Testing olark", "timestamp": "1445960829.592606", "kind": "MessageToOperator", "nickname": "United Kingdom (Rickmansworth)
#5043", "visitor_nickname": "United Kingdom (Rickmansworth) #5043"}, {"body": "Hello there", "timestamp": "1445960834.471775", "kind": "MessageToVisitor", "nickname": "Jessica Wood ", "operatorId": "744399"}], "operators": {"744399": {"username": "winlotto.com", "emailAddress": "support@winnlotto.com", "kind": "Operator", "nickname": "Jessica Wood ", "id": "744399"}}, "visitor": {"city": "Rickmansworth", "kind": "Visitor", "conversationBeginPage": "http://www.winnlotto.com/", "countryCode": "GB", "ip": "195.110.84.183", "chat_feedback": {}, "operatingSystem": "Windows", "emailAddress": "", "country": "United Kingdom", "organization": "COLT Technology Services Group Limited", "fullName": "United Kingdom (Rickmansworth) #5043", "id": "tTOFv5oa0muGA16s7281C5P1GOAsjJA4", "browser": "Firefox 41.0"}, "isLead": "true", "id": "rWpAfF48ITi4y6DU7281C2R1GP0FHVJ3"}

在开头看到这个data=。他们将 json 作为值中的数据参数发送,这很有趣,但我不知道如何在 web.api Controller 中接受它。我试过 [FromBody] 字符串数据,它似乎不起作用。

这是接受它的我的 Action :

[Route("Index")]
        [HttpPost]
        public IHttpActionResult Index([FromBody] string data)
        {
            var body = string.Empty;
            using (var reader = new StreamReader(Request.Content.ReadAsStreamAsync().Result))
            {
                reader.BaseStream.Seek(0, SeekOrigin.Begin);
                body = reader.ReadToEnd();
            }

            return Ok();
        }

编辑: 我所做的是创建带有字符串数据字段的模型,它在字符串中检索 json:

public class ServiceModel
{
    public string data { get; set; }
}

这是检索表单参数的正确方法吗?

最佳答案

您要做的是创建一个模型来表示您期望的对象。调用者将发送格式为 json 的对象,Web API 可以自动将其反序列化为 c# 对象。在该对象中,您可以轻松地对模型进行验证,对该数据进行一些处理,并返回一个结果,该结果也可以自动反序列化回 json(如果这是调用者想要的)。

我建议您研究/阅读核心 Web API 概念,因为这是相当基础的。您不希望开始实现和支持您不完全理解的解决方案。那里有很多很棒的资源,如果您更喜欢动手操作,那么搜索一些教程,如果您更喜欢更详细的信息,那么从一本书或深入的解释开始。

这里有一些代码可以帮助您入门。这些类基于您提供的 JSON。

public class Item {
   public string Body {get;set;}
   public string TimeStamp {get;set;}
   // rest of properties
}
public class SomeObject {
   public string Kind {get;set;}
   public string[] Tags  {get;set;}
   public Item[] Items {get;set;}
   // rest of properties
}


// your method in the web api controller
public IHttpActionResult Index([FromBody] SomeObject myObject) {
 // your validation and action code here and then return some result
}

// update your web api configuration registration to convert camel case json to pascal cased c# and back again
public static class WebApiConfig {
        public static void Register(HttpConfiguration config)
        {
            // makes all WebAPI json results lower case
            var json = GlobalConfiguration.Configuration.Formatters.JsonFormatter;
            json.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
// rest of code

关于c# - Web.Api 接受参数形式的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33373588/

相关文章:

c# - "8"的 int.Parse 失败。 int.Parse 总是需要 CultureInfo.InvariantCulture?

c# - Entity Framework 代码优先 : how to add more props on model and update database?

asp.net - 在ASP.Net MVC应用程序中的哪里放置初始化代码?

c# - 我如何替换 Web API 模型绑定(bind)的行为,以便在没有传入参数时收到一个新实例而不是 Null

javascript - Kendo Grid 和 ui-sref 四舍五入数

c# - 编译器是否优化了字符串文字?

c# - 跨不同屏幕尺寸缩放 WPF 应用程序中的元素

c# - 在 C# 中抓取 Windows 应用程序的屏幕

c# - 无法使用 Dapper 获取 Long 类型的数据

asp.net-mvc - 如何解决 "HTTP Error 500.19 - Internal Server Error" "<remove name="ExtensionlessUrlHandler-Integrated-4。 0"/>"