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>


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM