如何使{控制器} / {ID} / {}行动中MVC4工作? [英] How to make {controller}/{id}/{action} work in MVC4?

查看:118
本文介绍了如何使{控制器} / {ID} / {}行动中MVC4工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我用尽了一切办法,但貌似我只是没有得到它。我WebApiConfig.cs看起来是这样的:

I've tried everything but looks like I'm just not getting it at all. My WebApiConfig.cs looks like this:

config.Routes.MapHttpRoute(
    "Default",
    "api/{controller}/{id}",
    new { id = RouteParameter.Optional });

config.Routes.MapHttpRoute(
    "AccountVerification",
    "api/{controller}/{id}/{action}",
    null,
    new { controller = "Account" });

和我的控制器是这样的:

And my controller looks like this:

public class AccountController : ApiController {
    public HttpResponseMessage GetByKey(Guid accountID) {
        ...
    }

    [HttpGet]
    [ActionName("Verify")]
    public HttpResponseMessage VerifyAccount(Guid accountID) {
        ...
    }
}

这些方法应该得到一击与以下网址:

These methods should get a hit with the following URLs:

GET /api/account                                        - WORKS
GET /api/account/00000000-0000-0000-000000000001        - WORKS
GET /api/account/00000000-0000-0000-000000000001/verify - DOESNT WORK

我已经尝试了很多东西;我肯定在这里做得不对......请帮助。

I've tried a lot of things; I am definitely doing something wrong here...please help.

推荐答案

首先,如果你想用假GUID来测试,以及具有可选的Guid参数,它们必须是空的参数的(假的GUID将被反序列为空)

First, if you want to test with fake Guids, as well as having optional Guid parameters, they must be Nullable parameters (fake guids will be deserialized as null) :

public class AccountController : ApiController
{
    public HttpResponseMessage GetByKey(Guid? accountID)
    {
        throw new Exception("GetByKey " + (accountID.HasValue ? accountID.ToString() : "NULL"));
    }

    [System.Web.Http.HttpGet]
    [System.Web.Http.ActionName("Verify")]
    public HttpResponseMessage VerifyAccount(Guid? accountID)
    {
        throw new Exception("VerifyAccount "+(accountID.HasValue?accountID.ToString():"NULL"));
    }
}

那么,你的映射应该:

then, your mapping should :


  • 先用最具体的路线

  • 使用正确的参数名称

  • 使用正确的默认设置行为

  • use the most specific route first
  • use the correct parameters names
  • use the correct defaults for actions

config.Routes.MapHttpRoute(
    "AccountVerification",
    "api/{controller}/{accountID}/{action}"
    );


config.Routes.MapHttpRoute(
    "Default",
    "api/{controller}/{accountID}",
    defaults: new { Controller="Account", action = "GetByKey", accountID = RouteParameter.Optional }
    );


这篇关于如何使{控制器} / {ID} / {}行动中MVC4工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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