有多个参数的Web API路由 [英] Web API routing with multiple parameters

查看:182
本文介绍了有多个参数的Web API路由的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图找出如何做路由以下的Web API控制器:

I'm trying to work out how to do the routing for the following 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)
    {
        ...
    }
}

目前,我使用这个路由的网址:

At the moment, I'm using this routing for the URLs:

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格式或路由完全错了吗?路由看起来像黑魔法我...

but only the first method (with 2 parameters) is working at the moment. Am I on the right lines, or have I got the URL format or routing completely wrong? Routing seems like black magic to me...

推荐答案

问题是你的 API / myController的/ GetRowsOfType /用户名/ tableName值/ ROWTYPE URL将始终匹配第一条路线所以第二个是从未达到。

The problem is your api/MyController/GetRowsOfType/userName/tableName/rowType URL will always match the first route so the second is never reached.

简单的修复,先注册你的 RowsByType 路线。

Simple fix, register your RowsByType route first.

这篇关于有多个参数的Web API路由的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆