如何使用URL api rest url的url分段和查询字符串的组合来配置url

时间:2016-05-19 21:00:44

标签: c# asp.net-web-api asp.net-web-api-routing

(使用Web api 1.0) 我有一个场景,我的动作有多个参数,如 GetCustomer(int id,string email) 将url指定为

GET API /客户/ {ID} / {电子邮件}

但我希望将网址配置为

API /客户/ {ID}?电子邮件= {电子邮件}

因此,如果使用查询字符串进行网址分段,这是一个组合。目前,当我试图设置这个时,我得到以下错误。

路径网址不能以'/'或'〜'字符开头,也不能包含'?'字符。 参数名称:routeUrl

public class RouteConfig
{
    public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

        routes.MapRoute(
            name: "Default",
            url: "{controller}/{action}/{id}",
            defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
        );

        routes.MapRoute(
         "Help Area",
         "",
         new { controller = "Help", action = "Index" }
     ).DataTokens = new RouteValueDictionary(new { area = "HelpPage" });

    }
}

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {                                                                             

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

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

请提前帮助我解决此问题

1 个答案:

答案 0 :(得分:2)

您的配置需要更新

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config) {

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

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

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

如果您向api/Customer/{id}?email={email}

发出请求

活页夹会自动将GetCustomer(int id, string email)与网址中的email参数匹配