Web.Api接受参数表单值

时间:2015-10-27 16:38:03

标签: 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控制器中接受它。我试过[FromBody]字符串数据,它似乎没有用。

这是我接受它的行动:

[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();
        }

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

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

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

2 个答案:

答案 0 :(得分:0)

您要做的是创建一个代表您期望的对象的模型。调用者将发送格式为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

答案 1 :(得分:0)

可能model binder是最好的方式。

例如,假设我有这个控制器:

[RoutePrefix("bindingTest")]
public class BindingTestController : ApiController
{
    [Route("")]
    [HttpPost]
    public HttpResponseMessage Post([FromBody]Product data)
    {
        return Request.CreateResponse();
    }
}

但客户端正在以表格 - urlencoded格式向我发送数据,并在data参数中显示JSON数据:

client.PostAsync(url, new FormUrlEncodedContent(new[] 
{ 
    new KeyValuePair<String, String>("data", "{'Id': 0,'Name': 'string'}") 
}));

然后我可以创建一个自定义模型绑定器来读取这样的属性,从JSON反序列化Product对象并将正确的对象发送到控制器中的action方法:

// Raw prototype code
public class JsonFromDataVariable : IModelBinder
{
    public bool BindModel(HttpActionContext actionContext, ModelBindingContext bindingContext)
    {
        if (bindingContext.ModelType != typeof(Product))
        {
            return false;
        }

        var value = bindingContext.ValueProvider.GetValue("data");
        if (value != null && value.RawValue != null)
        {
            var serializer = new JsonSerializer();
            var product = JsonSerializer
                                .Create()
                                .Deserialize<Product>(new JsonTextReader(new StringReader(value.RawValue.ToString())));
            bindingContext.Model = product;
            return true;
        }

        return false;
    }
}

public class JsonFromDataVariableProvider : ModelBinderProvider
{
    public override IModelBinder GetBinder(System.Web.Http.HttpConfiguration configuration, Type modelType)
    {
        return new JsonFromDataVariable();
    }
}

请记住在模型中指明活页夹:

[ModelBinder(typeof(JsonFromDataVariableProvider))]
public class Product
{
    public int Id { get; set; }
    public string Name { get; set; }
}