http服务 Web API的使用

http服务 Web API的使用

一.概念:

Web API是网络应用程序接口。

详情百度百科:

http://baike.baidu.com/link?url=X1l2dlU9FlQmupX24-9qoZ9WHtU_baub9GsLJqKfO7G425mmpGEsU_yLCLjuMDVbmxr3EgwHXHTGxSEfp0sm26Hb3gevnVMw5Fvzgtl2TjW

 

二.Demo:

1.新建项目WebApi_Demo

2.选择Web API模板:

3.新建控制器TestController.css

注意:模板选择空API控制器

3.访问api接口:

api/Test/Get

默认返回的是xml

如下配置后可以返回json

 

 

 

4.控制器代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using System.Web.Mvc;

namespace WebApi_Demo.Controllers
{
    public class TestController : ApiController
    {
        // GET api/Tes/5
        public string Get(int id)
        {
            return "hellow web api!";
        }

        // GET api/Tes/5
        public Person Get()
        {
            var p = new Person();
            p.Name = "张三";
            p.Age = 18;//张三一直年轻
            return p;
        }

        // GET api/Tes/5
        public JsonResult GetPerson()
        {
            var p = new Person();
            p.Name = "张三";
            p.Age = 18;//张三一直年轻

            var json = new JsonResult();
            json.Data = p;
            json.JsonRequestBehavior = JsonRequestBehavior.AllowGet;
            return json;
        }

    }


    public class Person
    {
        public string Name { get; set; }

        public int Age { get; set; }
    }
}

 

三.配置:

1.返回json格式:

首先找到Global.asax文件:

配置:

经过测试只要清除就可以了

GlobalConfiguration.Configuration.Formatters.XmlFormatter.SupportedMediaTypes.Clear();

//清除返回使用xml格式
GlobalConfiguration.Configuration.Formatters.XmlFormatter.SupportedMediaTypes.Clear();

//
添加返回使用json格式 GlobalConfiguration.Configuration.Formatters.JsonFormatter.MediaTypeMappings.Add(new QueryStringMapping("json", "true", "application/json"));

 

2.通过action访问:

在WebApiConfig.cs文件中配置

切记:如果不想删除默认的路由,那么把这条路由放到前面

 

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

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

 3.删除和更新接口错误提示:

调用wewb api 中的put和delete报错,Method Not Allowed 405错误。

原因是,安全起见,api一般不允许操作修改和删除的。

解决方案:

在web.config中增加这些代码:

<system.webServer>

<--增加的代码start-->

 <validation validateIntegratedModeConfiguration="false"/>
    <modules runAllManagedModulesForAllRequests="true">
      <remove name="WebDAVModule"/>
    </modules>

<--增加的代码end-->
</system.webServer>

posted @ 2017-01-12 17:30  土豆哥  阅读(2811)  评论(0编辑  收藏  举报