根据主题,我创建了两个MVC web api示例,其中JSON作为输入和输出。
样品放置
[HttpPut]
public string Put(int id, [FromBody] dynamic value)
{
return id.ToString() + value.name + value.time;
}
示例获取
[HttpGet]
public string Get()
{
Portal.BusinessLogic.User.FAQHelper faqHELPER = new Portal.BusinessLogic.User.FAQHelper();
return JsonConvert.SerializeObject(faqHELPER.getFAQs()); ;
}
但是,我不确定这是否是接受并返回json字符串的Web控制器的正确方法。任何人都可以指导我如何以高效和安全的方式做到这一点吗?
答案 0 :(得分:1)
其中一种方法几乎是一种默认方式,就是将您的参数和返回类型作为您保存和检索的数据的模型。在这种情况下,您的控制器将如下所示:
// [HttpPut] <-- This is not needed if method called "Put...."
public HttpResponseMessage Put (MyDataPOCOModel model)
{
// update your data
}
// [HttpGet] <-- This is not needed if method called "Get...."
public HttpResponseMessage Get(int id)
{
// Get the data, pack HttpResponseMessage and return
// Optionally, return can be just MyDataPOCOModel
}
//[HttpGet] <-- This is not neededif method called "Get...."
public HttpResponseMessage Get()
{
// Get the data, pack HttpResponseMessage and return
// Optionally, return can be just IEnumerable<MyDataPOCOModel>
}
如果您的代码与上面的代码类似,默认情况下,web api
会自动将Model对象序列化/反序列化为JSON