简体   繁体   English

在WebAPI中读取动态对象FromBody无效

[英]Reading dynamic object FromBody in WebAPI just doesn't work

I found a lot of info about this topic, but none of those sites and articles could solve my problem. 我找到了很多有关该主题的信息,但是这些站点和文章都无法解决我的问题。 I'm having a pretty simple method: 我有一个非常简单的方法:

[HttpPost, Route("Diagnosis/{lkNo}/Tree/{nodeID:int}/Answer")]
public List<TreeNode> AnswerTreeNode(string lkNo, int nodeID, 
[FromBody] dynamic data) {
    // So some stuff
}

When I call that method, it fills the first two parameters, but data is always null. 当我调用该方法时,它会填充前两个参数,但数据始终为null。 Here's my test request as received by the server: 这是服务器收到的我的测试请求:

POST /Diagnosis/LK-28084453/Tree/0/Answer HTTP/1.1
Cache-Control: no-cache
Connection: keep-alive
Accept: */*
Accept-Encoding: gzip, deflate
Cookie: ASP.NET_SessionId=*****; __RequestVerificationToken=*****
Host: localhost:51124
User-Agent: PostmanRuntime/7.6.0
Postman-Token: *****
Content-Length: 5
Content-Type: application/x-www-form-urlencoded

=Test

Sending the parameter as json leads to the same result: 将参数作为json发送会导致相同的结果:

...
Content-Length: 25
Content-Type: application/json

{ "value": "some value" }

Whatever I try, data is always null. 无论我尝试什么,数据始终为空。 Here's my route config: 这是我的路线配置:

// WebAPI
GlobalConfiguration.Configure(config => {
    config.MapHttpAttributeRoutes();

    config.Routes.MapHttpRoute(
        name: "DiagnosisApi",
        routeTemplate: "api/{controller}/{id}",
        defaults: new { id = RouteParameter.Optional }
    );

    // Default return JSON
    config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new System.Net.Http.Headers.MediaTypeHeaderValue("text/html"));
    config.Formatters.JsonFormatter.SerializerSettings.ContractResolver =
        new Newtonsoft.Json.Serialization.CamelCasePropertyNamesContractResolver();

    config.MessageHandlers.Add(new MyHandler());
});

public class MyHandler : System.Net.Http.DelegatingHandler {
    protected override async System.Threading.Tasks.Task<System.Net.Http.HttpResponseMessage> SendAsync(
                                             System.Net.Http.HttpRequestMessage request,
                                                System.Threading.CancellationToken token) {
        System.Net.Http.HttpMessageContent requestContent = new System.Net.Http.HttpMessageContent(request);
        string requestMessage = requestContent.ReadAsStringAsync().Result; // This one contains the raw requests as posted abve

        return await base.SendAsync(request, token);
    }
}

Do you have an idea, what's wrong here? 你有什么主意,这是怎么了?

My suggestion would be to not use the dynamic type in your method signature. 我的建议是在方法签名中不要使用动态类型。

Change it to string and make sure you serialize what you are sending to the api as well. 将其更改为字符串,并确保对发送给api的内容进行序列化。

Once you see the data coming in then you can use something like Newtonsoft Json to parse the string into a dynamic object and you can take it from there. 一旦看到数据输入,就可以使用Newtonsoft Json之类的东西将字符串解析为动态对象,然后从那里获取它。

Your method would become : 您的方法将变为:

public List<TreeNode> AnswerTreeNode(string lkNo, int nodeID, 
[FromBody] string data) {
    // parse data into dynamic here
}

I solved the problem by removing my temporary message handler. 我通过删除临时消息处理程序解决了该问题。 Also, I changed the data attribute to Newtonsoft's JObject type. 另外,我将data属性更改为Newtonsoft的JObject类型。 Now I can easily implement my own routine to interpret the received data. 现在,我可以轻松实现自己的例程来解释接收到的数据。 For example: 例如:

if (data["result"].Type == JTokenType.Boolean && data["result"].Value<bool>())

Here's my Javascript code: 这是我的Javascript代码:

node.treat = function (result) {
    if (result !== undefined)
        $.ajax({
            url: 'Diagnosis/' + vm.data.lkNo() + '/Tree/' + node.id + '/Answer',
            data: JSON.stringify({ result: result }),
            type: 'POST',
            contentType: "application/json",
            success: function (response) { /* do something */ }
        };
}

Works like a charm! 奇迹般有效!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM