首页 文章

MVC url中的否定参数

提问于
浏览
1

在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

    您可以尝试使用URL编码 - 符号 .

    /MyController/Action/%2D123/type
    

    我认为问题在于路由将其视为分隔符 . 如果你URL encode - ,它应该作为值传递 .

  • 0

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

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

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

    只需更新你的 .

相关问题