Reputation: 125
I have an ASP.NET Web API action:
[HttpPost]
public void test(myCustomObj Entity)
{
}
And the JSON data is:
{
"ID": "1",
"Name": "ilhan",
"surname": "aksu"
}
So far my code works well. However, when I add a new primitive parameter:
[HttpPost]
public void test(myCustomObj Entity, [FromBody] string strdata)
{
}
and when I post the following JSON:
{
"Entity": {
"ID": "1",
"Name": "ilhan",
"surname": "aksu"
},
"strdata": "testdata"
}
the server returns 500 Internal Server Error.
How can I format my JSON data or change my action method to fix this problem?
Upvotes: 2
Views: 2946
Reputation: 3139
If you're posting json, you could accept a string
parameter:
[HttpPost]
public void Test(string jsonString)
{
}
And maybe a serializer helper to avoid polluting the code:
public static class JsonSerializer
{
public static string Serialize<T>(T t) where T : class
{
return JsonConvert.SerializeObject(t);
}
public static T Deserialize<T>(string s) where T : class
{
return (T)JsonConvert.DeserializeObject(s, typeof(T));
}
}
Then in your method you can materialize the json payload:
[HttpPost]
public void Test(string jsonString)
{
var o = JsonSerializer.DeserializeObject(jsonString, typeof(MyObject));
// ...
}
And if you're returning json, it could be as follows:
[HttpGet]
public JsonResult GetTest()
{
var i = YourService.GetSomethingById(1);
iSerialized = JsonSerializer.Serialize(i);
return new JsonResult
{
ContentEncoding = System.Text.Encoding.UTF8,
ContentType = "application/json",
JsonRequestBehavior = JsonRequestBehavior.AllowGet,
Data = iSerialized
};
}
Upvotes: 2
Reputation: 1038810
As always write a view model
public class MyViewModel : myCustomObj
{
public string Strdata { get; set; }
}
Now have your controller action take this view model as argument:
[HttpPost]
public void test(MyViewModel model)
{
...
}
and now you could hit your action with the following JSON payload:
{"ID":"1","Name":"ilhan","surname":"aksu","strdata":"testdata"}
and everything's gonna get properly bound.
Alternatively your view model might look like this:
public class MyViewModel
{
public myCustomObj Entity { get; set; }
public string Strdata { get; set; }
}
and now you could hit your action with this payload:
{"Entity":{"ID":"1","Name":"ilhan","surname":"aksu"},"strdata":"testdata"}
So it's basically up to you to decide how your view model will look like depending on the JSON payload that you would like to use to call your controller action. So, never think of having more than 1 action argument in a controller action. Always think in terms of how your view model will look like.
Yes, controller actions always take view models as arguments and always return view models. That's the correct design. In ASP.NET MVC and in ASP.NET Web API.
Upvotes: 0