.net WebApi

1. Create a project

2. Configure routing - Original

 

3. Start project

 

We find that, as with Action can not call a method like MVC, and the prompt return of data Xml, obviously this is not the result we want, then we need to modify the route with Syria

4. Modify the routing - call it a manner consistent with the results you want

    public static void Register(HttpConfiguration config)
    {
      // Web API 配置和服务

      // Web API 路由
      config.MapHttpAttributeRoutes();
    
      config.Formatters.Clear();
      config.Formatters.Remove(config.Formatters.XmlFormatter);
      config.Formatters.Add(new JsonMediaTypeFormatter());
      config.Formatters.JsonFormatter.SerializerSettings = new JsonSerializerSettings
      {
          DateFormatString = "yyyy-MM-dd HH:mm:ss",//解决json时间带T的问题
          Formatting = Newtonsoft.Json.Formatting.Indented,//解决json格式化缩进问题
          ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore//解决json序列化时的循环引用问题
      };
  
      config.Routes.MapHttpRoute(
          name: "DefaultApi",
          routeTemplate: "api/{controller}/{action}/{id}",
          defaults: new { id = RouteParameter.Optional }
      );
    }

5.测试  --符合预期

6.解决  -- 跨域问题

1   <system.webServer>
2     <httpProtocol>
3       <customHeaders>
4         <add name="Access-Control-Allow-Origin" value="*" />
5         <add name="Access-Control-Allow-Headers" value="*" />
6         <add name="Access-Control-Allow-Methods" value="GET, POST, PUT, DELETE" />
7       </customHeaders>
8     </httpProtocol>
9   </system.webServer>

7.结束

后续  WebApi 传参 方式。。。

 

Guess you like

Origin www.cnblogs.com/lsw-asks/p/11234607.html