在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>
}
可能是一种更改此默认行为的方法吗?
答案 0 :(得分:0)
答案 1 :(得分:0)
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { },
constraints: new { controller = "Home", action = @"([Ii])ndex", id = @"-?\d+"}
);
我得到-ve值......
同样更新你的。