c# - 具有多个参数的 Web API 路由

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

我正在尝试找出如何为以下 Web API Controller 进行路由:

public class MyController : ApiController
{
    // POST api/MyController/GetAllRows/userName/tableName
    [HttpPost]
    public List<MyRows> GetAllRows(string userName, string tableName)
    {
        ...
    }

    // POST api/MyController/GetRowsOfType/userName/tableName/rowType
    [HttpPost]
    public List<MyRows> GetRowsOfType(string userName, string tableName, string rowType)
    {
        ...
    }
}

目前,我正在为 URL 使用此路由:

routes.MapHttpRoute("AllRows", "api/{controller}/{action}/{userName}/{tableName}",
                    new
                    {
                        userName= UrlParameter.Optional,
                        tableName = UrlParameter.Optional
                    });

routes.MapHttpRoute("RowsByType", "api/{controller}/{action}/{userName}/{tableName}/{rowType}",
                    new
                    {
                        userName= UrlParameter.Optional,
                        tableName = UrlParameter.Optional,
                        rowType= UrlParameter.Optional
                    });

但目前只有第一种方法(带有 2 个参数)有效。我是在正确的路线上,还是我的 URL 格式或路由完全错误?路由对我来说就像黑魔法...

最佳答案

我看到 WebApiConfig 变得“失控”,其中放置了数百条路由

相反,我个人更喜欢 Attribute Routing

您正在使它与 POST 和 GET 混淆

[HttpPost]
public List<MyRows> GetAllRows(string userName, string tableName)
{
   ...
}

HttpPostGetAllRows ?

为什么不这样做:

[Route("GetAllRows/{user}/{table}")]
public List<MyRows> GetAllRows(string userName, string tableName)
{
   ...
}

或更改为 Route("PostAllRows"和 PostRows 我认为您确实在执行 GET 请求,因此我显示的代码应该适合您。您来自客户端的调用将是 ROUTE 中的任何内容,因此它会找到您的METHOD 与 GetAllRows,但方法本身,该名称可以是您想要的任何名称,因此只要调用者与 ROUTE 中的 URL 匹配,如果您真的愿意,您可以为该方法放入 GetMyStuff。

更新:

我实际上更喜欢显式HTTP方法 而且我更喜欢将路由参数与方法参数相匹配

[HttpPost]
[Route("api/lead/{vendorNumber}/{recordLocator}")]
public IHttpActionResult GetLead(string vendorNumber, string recordLocator)
{ .... }

(路由 lead 不需要与方法名称 GetLead 匹配,但您需要在路由参数和方法参数上保持相同的名称,即使您可以更改顺序,例如将 recordLocator 放在 vendorNumber 之前,即使路线是相反的 - 我不这样做,因为为什么看起来更困惑)。

奖励: 现在您也可以随时在路由中使用 regex,例如

[Route("api/utilities/{vendorId:int}/{utilityType:regex(^(?i)(Gas)|(Electric)$)}/{accountType:regex(^(?i)(Residential)|(Business)$)}")]
public IHttpActionResult GetUtilityList(int vendorId, string utilityType, string accountType)
    {

关于c# - 具有多个参数的 Web API 路由,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21140305/

相关文章:

c# - C++ cli ref class 数组转换为指针

asp.net-mvc - ASP.NET Web Api 元数据交换?

asp.net-web-api - 反序列化 HttpError ModelState

ASP.NET 4 WebAPI : route with back slash

c# - Web api中的多个POST请求

c# - 如何将DropDownList选定的值分配给SqlDataSource?

c# - Microsoft.AspNet.WebApi.OData 和 Microsoft.Data.OData 和 Microsoft.AspNet.OData 之间有什么区别?

c# - while (reader.Read()) 会自动关闭吗?

.net - 分析 Service Fabric 应用程序

asp.net - 从mvc4迁移到mvc5,属性路由不起作用