MVC url中的否定参数

时间:2014-11-25 19:32:00

标签: asp.net-mvc asp.net-mvc-4 asp.net-mvc-routing

在MVC路由引擎中,“/ MyController / Action / -123 / type”的URL和路由规则为:

routes.MapRoute(name: "AddRemoveRequestee",
           url: "{controller}/{action}/{requestId}/{someOtherData}",
           defaults: new { },
           constraints: new { controller = "MyController", action = @"[Aa]ction", requestId = @"-?\d+"});

MVC将调用控制器的Action(int requestId,string someOtherData)方法,但它将传递123作为requestId的值,而不是正确的-123值。

是否有更优雅的方式处理此问题:

    //HACK:Fix to handle when MVC annoyingly makes negative values in the url positive
    private int FixNegativeParameter(int id, int paramPos=-1)
    {
        //HACK:Check the raw URL against what MVC passed in.
        string rawUrl = this.Request.RawUrl;
        var urlParts = rawUrl.Split(@"/?".ToCharArray(), StringSplitOptions.None);
        if (paramPos >= 0)
            //Parameter is specified explicitly
            return urlParts[paramPos] == "-" + id ? -id:id;
        //Position not specified.  Looks for any instance of the negative of id
        //HACK:  Not totally reliable if url has multiple int arguments
        return urlParts.Any(up => ("-" + id) == up) ? -id : id;
    }

    [HttpPost]
    public JsonResult Action(int requestId, int profileId)
    {
        requestId = FixNegativeParameter(requestId);
        <remainder of code that accepts negative ids as valid>
    }

可能是一种更改此默认行为的方法吗?

2 个答案:

答案 0 :(得分:0)

您可以尝试对#符号进行URL编码。

/MyController/Action/%2D123/type

我认为问题在于路由会将其作为分隔符而丢弃。如果您URL encode -,则应将其作为值传递。

答案 1 :(得分:0)

好的,再看一遍......看起来你的路线还不完整 - 你的行动中缺少一个支架......

        routes.MapRoute(
            name: "Default",
            url: "{controller}/{action}/{id}",
            defaults: new { },
            constraints: new { controller = "Home", action = @"([Ii])ndex", id = @"-?\d+"}
       );

我得到-ve值......

同样更新你的。