MVC网页API路由默认动作不灵 [英] MVC Web Api Route with default action not working

查看:130
本文介绍了MVC网页API路由默认动作不灵的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的的TestController 我有以下内容:

 [HttpGet]
    public IEnumerable<String> Active()
    {
        var result = new List<string> { "active1", "active2" };

        return result;
    }

    [HttpGet]
    public String Active(int id)
    {
        var result = new List<string> { "active1", "active2" };

        return result[id];
    }

RouteConfig 的映射是:

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

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

在浏览器下面的请求如下:

In a browser the following request works:

api/test/active/1

但是,这返回内部服务器错误

api/test/active

你有什么做的,返回的动作的可能或maynot有一个参数,以类似的方式为默认获取?

What do you have to do to return a action that may or maynot have a parameter in a similar manner to the default Get?

更新1
作为勒的Cuong建议,改变路线的帮助顺序,路线现在:

Update 1 As Cuong Le suggested, changing the ordering of routes helped, the routes are now:

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

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

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

我不得不删除行动=从ActionApi路线,否则标准获取其他控制器停止工作(即API /值)

I had to remove action = "" from the ActionApi route otherwise the standard Get on the other controllers stopped working (i.e. api/values)

API /测试/主动现已解决,但现在我得到了500内部服务器错误的/ API /测试它possile同时拥有议决,所以API /测试将返回所有和/测试/活跃,只有回归一些?

api/test/active is now resolving, but I now get a 500 Internal Server Error for /api/test is it possile to have both resolves, so api/test would return "all" and /test/active only return "some"?

推荐答案

要做到这一点是提供参数的默认值的一种方式,

One way to do it is to provide a default value for the parameter,

[HttpGet]
public String Active(int id = 0)
{
    var result = new List<string> { "active1", "active2" };

    if (id == 0) {
      return result;
    } else {
      return result[id];
    }
}

这篇关于MVC网页API路由默认动作不灵的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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