asp.net mvc实现rest风格返回json

实现类似:http://localhost:1799/rest/person/1方式返回一个json内容:

在asp.net mvc中新建一个control rest,然后在其中新增方法:

1 public IActionResult Person(int id)
2 {
3     return Content("{"id":""+id+"","name":"张三"}");
4 }

运行程序在IE浏览器中输入:

http://localhost:1799/rest/person/1

当然可能有多个参数的情况如下同时直接以Json的形式而不是上例中通过拼接字符的方式:

        public IActionResult Person2(int id,string name)
        {
            Models.Person p = new Models.Person();
            p.id =id;
            p.name = name;
            return Json(p);
        }    

对于这种显然需要进行路由映射添加如下:

routes.MapRoute(
name: "rest",
template: "{controller=rest}/{action=person2}/{id?}/{name?}");

运行程序在浏览器中输入:

http://localhost:1799/rest/person/1/张三

查看 结果已经返回,当然这个实现思路比较简单点。

这样我们就可以通过jquery等以json形势去调用了

原文地址:https://www.cnblogs.com/devgis/p/4994620.html