《Asp.Net Web API》 ----路由机制

 

 

本文参考

https://blog.csdn.net/zhoukun1008/article/details/52704651

一、路由表

在ASP.NET Web API中,一个控制器是处理HTTP请求的一个类,控制器里的Public方法是一个动作方法,当Web API框架接收到一个请求,它将这个请求路由到一个动作

为了确定调用哪个动作,框架使用了一个路由表定义在App_Start目录下的WebApiConfig.cs文件

。Web API的默认路由模板是“api/{controller}/{id}”。在这个模板中,“api”是一个文字式路径片段,而{controller}和{id}则是占位符变量。

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

namespace MvcApplication1
{
    public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
               // routeTemplate:"{controller}/{action}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );

            // 取消注释下面的代码行可对具有 IQueryable 或 IQueryable<T> 返回类型的操作启用查询支持。
            // 若要避免处理意外查询或恶意查询,请使用 QueryableAttribute 上的验证设置来验证传入查询。
            // 有关详细信息,请访问 http://go.microsoft.com/fwlink/?LinkId=279712//config.EnableQuerySupport();

            // 若要在应用程序中禁用跟踪,请注释掉或删除以下代码行
            // 有关详细信息,请参阅: http://www.asp.net/web-api
            config.EnableSystemDiagnosticsTracing();
        }
    }
}
View Code

 

二、更改路由表默认设置

       由Controller来确定访问哪个类,再根据Action来确定访问哪个方法

2.1  修改配置文件

    找到WebApiConfig.cs文件  将原来的routeTemplate: "api/{controller}/{id}",更改为 routeTemplate:"{controller}/{action}/{id}",

2.2  修改控制器中对应的方法

  添加 [HttpGet]    QueryAllProducts()   ----方法名   

代码

/// <summary>
        /// 查询所有产品
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public IEnumerable<Product> QueryAllProducts() {
            return products;
        }

        /// <summary>
        /// 根据id查询
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet]
        public Product QueryProductById(int id) {

            var product = products.FirstOrDefault((p) => p.Id == id);
            if (product == null) {
                throw new HttpResponseException(HttpStatusCode.NotFound);
            }
            return product;
        }

        /// <summary>
        /// 根据种类查询商品
        /// </summary>
        /// <param name="category"></param>
        /// <returns></returns>
        [HttpGet]
        public IEnumerable<Product> QueryProductsByCategory(string category)
        {
            return products.Where(
                (p) => string.Equals(p.Category, category,
                    StringComparison.OrdinalIgnoreCase));
        }
View Code

 测试效果

 

 2.3 还可以使用注解属性来代替Action的使用

 代码

   /// <summary>
        /// 根据id查询
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet]
        [ActionName("Test")]
        public Product QueryProductById(int id) {

            var product = products.FirstOrDefault((p) => p.Id == id);
            if (product == null) {
                throw new HttpResponseException(HttpStatusCode.NotFound);
            }
            return product;
        }
View Code

测试效果

 

posted @ 2018-07-31 16:17  最初5628  阅读(107)  评论(0编辑  收藏  举报