简体   繁体   English

ASP.NET在URL中传递参数

[英]ASP.NET Passing Parameter in URL

I wrote a very simple web app in Flask and am porting it to ASP.NET Framework. 我在Flask中编写了一个非常简单的Web应用程序,并将其移植到ASP.NET Framework。 All the functionality is in JavaScript and HTMl, so the framework should just act as scaffolding. 所有功能都在JavaScript和HTMl中,因此框架应该只是作为脚手架。 I've got almost everything ported over, except for what seems to be a routing issue. 除了似乎是路由问题之外,我几乎已经移植了所有东西。 My site expects a string token variable to be appended to the URL, like so: www.mysite.com/token-string . 我的网站需要将一个字符串标记变量附加到URL,如下所示: www.mysite.com/token-string For development, the URL is localhost:*****/string-token , with my Index.cshtml page being displayed as default. 对于开发,URL是localhost:*****/string-token ,我的Index.cshtml页面显示为默认值。

When I pass the URL without the token it works fine and my index page loads. 当我在没有令牌的情况下传递URL时,它可以正常工作并加载我的索引页面。 However I get a 404 when I try it with the token. 但是,当我使用令牌尝试时,我得到了404。 I'm assuming it's identifying the token as a route and is trying to navigate to it? 我假设它将令牌识别为路线并试图导航到它? I'm not sure how to fix it. 我不确定如何解决它。 Here are the important parts of my code: 以下是我的代码的重要部分:

HomeController.cs: HomeController.cs:

public class HomeController : Controller
{
    public ActionResult Index(string token)
    {
        return View();
    }
}

RouteConfig.cs: NB: I've not changed this, not sure what to do with it. RouteConfig.cs:注意:我没有改变这个,不知道如何处理它。

public class RouteConfig
{
    public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

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

It's quite important that the token is passed in the way it is, rather than as a ? 令牌以它的方式传递是非常重要的,而不是像? query parameter or anything like that. 查询参数或类似的东西。 Additionally, the C# index view doesn't really need to do anything with the token - it gets extracted by the JavaScript. 此外,C#索引视图并不需要对令牌执行任何操作 - 它由JavaScript提取。

Any advice is most welcome. 任何建议都是最受欢迎的。 Thanks. 谢谢。

Each segment (ie {controller} ) in the route is a variable, and in the default route makes them all optional. 路径中的每个段(即{controller} )都是变量,而在默认路径中,它们都是可选的。 Therefore, your default route is matching the request www.mysite.com/token-string . 因此,您的默认路由与请求www.mysite.com/token-string匹配。

What you need to do is insert a route that has a constraint to only match URLs with your token. 您需要做的是插入一个具有约束的路由,以将URL与您的令牌匹配。 Assuming your token is a GUID, you could use a regex route constraint as follows: 假设您的令牌是GUID,您可以使用正则表达式路由约束 ,如下所示:

public class RouteConfig
{
    public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

        routes.MapRoute(
            name: "TokenRoute",
            url: "{token}",
            defaults: new { controller = "Home", action = "Index" },
            constraints: new { token = @"^[0-9A-Fa-f]{8}[-][0-9A-Fa-f]{4}[-][0-9A-Fa-f]{4}[-][0-9A-Fa-f]{4}[-][0-9A-Fa-f]{12}$" }
        );

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

If your token is not a GUID, you could either use a different regex or implement IRouteConstraint to ensure the route only matches your tokens. 如果您的令牌不是GUID,您可以使用不同的正则表达式或实现IRouteConstraint以确保路由仅匹配您的令牌。 The logic you use could be as simple as a == statement (as shown) or more complex (such as a database lookup). 您使用的逻辑可以像==语句(如图所示)一样简单,也可以更复杂(例如数据库查找)。

public static void RegisterRoutes(RouteCollection routes)
{
    routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

    routes.MapRoute(
        name: "TokenRoute",
        url: "{token}",
        defaults: new { controller = "Home", action = "Index" },
        constraints: new { token = new TokenConstraint() }
    );

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

public class TokenConstraint : IRouteConstraint
{
    public bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection)
    {
        if ((string)values[parameterName] == "MyToken")
        {
            return true;
        }

        return false;
    }
}

Note that you should use the route value key {token} in the url: parameter to match the action method parameter name token . 请注意,您应该使用url:参数中的路由值键{token}来匹配操作方法参数名称token

public ActionResult Index(string token)
{
    return View();
}

I guess you could try changing the default route to include token instead of id as shown below. 我猜您可以尝试更改默认路由以包含令牌而不是ID,如下所示。

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

The default Route pattern which you have expects the parameter with name as 'id' 您拥有的默认路由模式需要名称为“id”的参数

Either add (or modify the default route) like below route pattern 添加(或修改默认路由),如下面的路由模式

routes.MapRoute(
    name: "AnotherRoute", //your desired route name
    url: "{controller}/{action}/{token-string}",
    defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM