【问题标题】:Asp.Net Web API Routing - Required QueryString ParametersAsp.Net Web API 路由 - 必需的 QueryString 参数
【发布时间】:2012-09-05 20:41:24
【问题描述】:

如何在 Asp.Net Web API 中要求某些路由的查询字符串?

控制器:

public class AppleController : ApiController
{
    public string Get() { return "hello"; }
    public string GetString(string x) { return "hello " + x; }
}

public class BananaController : ApiController
{
    public string Get() { return "goodbye"; }
    public string GetInt(int y) { return "goodbye number " + y; }
}

所需路线:

/apple        --> AppleController  --> Get()
/apple?x=foo  --> AppleController  --> Get(x)
/banana       --> BananaController --> Get()
/banana?y=123 --> BananaController --> Get(y)

【问题讨论】:

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


    【解决方案1】:

    只要做这样的事情:

    public string Get(int y = -1)
    { 
        if(y < 0) return "goodbye"; 
        return "goodbye number " + y; 
    }
    

    这样它是一条路线,涵盖所有情况。为了清楚起见,您也可以将每个方法都分解为私有方法。

    另一种方法是添加更多路线,但由于这些路线有些特定,因此您必须添加额外路线。为简单起见,我会说您将方法 GetStringGetInt 更改为相同的东西(例如 GetFromId 以便您可以重用路由:

    routes.MapRoute(
        name: "GetFromIdRoutes",
        url: "{controller}/{id}",
        defaults: new { action = "GetFromId" }
    );
    
    routes.MapRoute(
        name: "GetRoutes",
        url: "{controller}",
        defaults: new { action = "Get" }
    );
    

    如果您没有使这些足够通用,您最终可能会得到很多路由条目。另一个想法是将这些放入区域以避免路由冲突。

    【讨论】:

    • 我希望有一些不那么“骇人听闻”的东西,但我想这将不得不这样做......
    • 我也将添加另一个路由方法 - 待命
    • 还添加了路由方法。
    【解决方案2】:

    您可以在路由中将查询字符串指定为可选或非(在 Global.asax 中):

        ' MapRoute takes the following parameters, in order:
        ' (1) Pages
        ' (2) ID of page
        ' (3) Title of page
        routes.MapRoute( _
            "Pages", _
            "Pages/{id}/{title}", _
            New With {.controller = "Home", .action = "Pages", .id = UrlParameter.Optional, .title = UrlParameter.Optional} _
        )
    

    这是 VB.NET。

    【讨论】:

    • 谢谢,但我正在寻找一种使用 QueryString 参数的方法
    • 你不能在你的动作中使用Public Function LogOn(ByVal model As LogOnModel, ByVal returnUrl As String) As ActionResult之类的东西吗?
    【解决方案3】:

    今天早上我有一个类似的问题,我想我找到了一种更简单的方法来配置我的路线。在你的情况下,使用这个:

    config.Routes.MapHttpRoute(
        name: "AppleRoute",
        routeTemplate: "apple",
        defaults: new { controller = "Apple" }
    );
    
    config.Routes.MapHttpRoute(
        name: "BananaRoute",
        routeTemplate: "banana",
        defaults: new { controller = "Banana" }
    );
    

    只需指定控制器,让框架根据您的查询字符串参数是否存在来选择正确的操作。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-10-09
      • 2012-04-27
      • 1970-01-01
      • 2017-08-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多