简体   繁体   English

如何从webapi控制器中的json反序列化参数

[英]How to deserialize parameter from json in webapi controller

seems like I have the most basic problem, yet I cannot find the documentation I need to solve it. 好像我有最基本的问题,但我找不到解决它所需的文档。

I have an mvc webapi controller: 我有一个mvc webapi控制器:

public class TestController : ApiController
{
    [HttpGet]
    public MyClass Other([FromUri]MyClass id)
    {
        id.Value++;
        return id;
    }        
}

public class MyClass
{
    public int Value {get;set;}
}

which I am executing from a HttpClient: 我正在从HttpClient执行:

using (var client = new System.Net.Http.HttpClient())
{
    client.BaseAddress = new System.Uri("http://localhost:31573/api/");
    client.DefaultRequestHeaders.Accept.Clear();
    client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
    var obj = new MyClass { Value = 3 };
    var data = JsonConvert.SerializeObject(obj);
    StringContent queryString = new StringContent(data, Encoding.UTF8, "application/json");
    var paramsValue = queryString.ReadAsStringAsync().Result;
    var response = client.GetAsync("Test/?id="+ paramsValue).Result;                    
    var textResponse = response.Content.ReadAsStringAsync().Result;
    var result = JsonConvert.DeserializeObject<MyClass>(textResponse);                    
 }

The problem is that the parameter id which is received by the controller is a default instance of MyClass (ie Value = 0). 问题是控制器接收的参数id是MyClass的默认实例(即Value = 0)。 If I change the prototype of the method to accept a string: 如果我更改方法的原型以接受字符串:

[HttpGet]
public MyClass Other([FromUri]string id)
{
    var val = JsonConvert.DeserializeObject<MyClass>(id);
    val.Value++;
    return val; 
}    

it all works fine, but I would rather not have to manually do the deserialization in every controller method. 一切正常,但我宁愿不必在每个控制器方法中手动执行反序列化。

I have tried many combinations of how I create the query string, so far having no luck. 我已经尝试了很多组合我如何创建查询字符串,到目前为止没有运气。

It appears that the data is getting to the webApi correctly, but the deserialization is not happening, so I suspect that I have not configure the webApi correctly to use json form the request parameters. 似乎数据正确到达webApi,但反序列化没有发生,所以我怀疑我没有正确配置webApi以使用json形式的请求参数。

my webapiconfig looks like: 我的webapiconfig看起来像:

public static void Register(HttpConfiguration config)
        {
            if (config == null)
                throw new ArgumentNullException(nameof(config));

            // Web API configuration and services
            config.Formatters.Clear();
            config.Formatters.Add(new JsonMediaTypeFormatter());

            // Web API routes
            config.MapHttpAttributeRoutes();

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

so its returning json correctly, but incoming parameters are not deserialized correctly. 所以它正确返回json,但传入的参数没有正确反序列化。

Can anyone help?? 谁能帮忙?

Thanks to the help from @Mostafizur Rahman, I came to the conclusion that a get method was not appropriate here, So I have changed to a Post method and pass the data in the body: 感谢@Mostafizur Ra​​hman的帮助,我得出的结论是get方法在这里不合适,所以我已经改为Post方法并将数据传递到正文中:

public class TestController : ApiController
{
    public MyClass PostMethod([FromBody]MyClass id)
    {            
        id.Value++;
        return id;
    }
}

public class MyClass
{
    public int Value {get;set;}
}

with the client side becoming: 与客户端成为:

using (var client = new System.Net.Http.HttpClient())
{
    client.BaseAddress = new System.Uri("http://localhost:31573/api/");
    client.DefaultRequestHeaders.Accept.Clear();
    client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
    var obj = new MyClass { Value = 3 };
    var data = JsonConvert.SerializeObject(obj);
    StringContent queryString = new StringContent(data, Encoding.UTF8, "application/json");
    var paramsValue = queryString.ReadAsStringAsync().Result;
    var response = client.PostAsync("Test/PostMethod",  queryString).Result;
    var textResponse = response.Content.ReadAsStringAsync().Result;
    var result = JsonConvert.DeserializeObject<MyClass>(textResponse);
}

this is the querystring that you'll need to form - 这是你需要形成的查询字符串 -

http://localhost:61817/api/Test?Value=3

Then the code changes like - 那么代码就像 -

var response = client.GetAsync("Test?Value="+ obj.Value).Result;

在此输入图像描述

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

相关问题 webapi在控制器中使用datetime反序列化JSON请求 - webapi deserialize JSON request with datetime in controller 如何在ASP.NET MVC 5控制器上从JSON反序列化为抽象参数 - How do I deserialize from JSON to an abstract parameter on an ASP.NET MVC 5 controller WebApi使用动态参数名称反序列化对象的JSON数组 - WebApi deserialize JSON array of objects with dynamic parameter names 如何在参数中使用“0”反序列化json主体 - How to deserialize json body with "0" in parameter 如何使用 javascript function 从 WebAPI Z594C103F2C6E04C31DAZAB059F01 发送 JSON 不带引号 - How to send JSON with javascript function from WebAPI controller without quotes WebAPI:从控制器构造函数检索GET参数 - WebAPI: Retrieve GET parameter from Controller Constructor ASP.NET Core 3.1:如何将驼峰 json 从 webapi 反序列化为 pascalcase - ASP.NET Core 3.1: How to deserialize camelcase json from webapi to pascalcase 如何在WebAPI的控制器中传递输出参数 - How to pass output parameter in a controller in an WebAPI 从WebAPI中的JSON仅反序列化特定的DateTime格式 - Deserialize only specific DateTime formats from JSON in WebAPI WebAPI:将URI参数反序列化为poco操作参数 - WebAPI: Deserialize URI parameter to poco action parameter
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM