【问题标题】:In ASP .NET Core API projects, can I route a query string parameter to a controller action without a query string name在 ASP .NET Core API 项目中,我可以将查询字符串参数路由到没有查询字符串名称的控制器操作吗
【发布时间】:2022-11-24 03:33:24
【问题描述】:

我打算使用的 URL 是这样的 https://localhost:44355/?G3​​s2s 相对于 https://localhost:44355/?value=G3s2s

目前的问题是,我无法将该 URL 路由到将所需查询字符串作为参数传递给控制器​​操作,如下所示:

`

[Route("")]
//When the domain is called, this function will be hit and will redirect the user to the associated URL, given that it exists

public IActionResult RedirectShortURL(string bitcode) <--- Attempting to pass "G3s2s"
        {
            //string shortUrl = SiteSettings.ShortUrlDomain + bitcode;
            //Uri enteredUrl = new Uri(shortUrl);
            //bitcode = HttpUtility.ParseQueryString(enteredUrl.Query).ToString();

            
            URL urlObj = _urlDAO.GetURLByBitcode(bitcode);

            if (urlObj != null)
            {
                return Redirect(urlObj.OriginalURL);
            }
            else
            {
                return NotFound();
            }
        }

`

我试图在 Startup.cs 中创建自定义路由端点,但到目前为止还没有给我带来好运。这是它目前的样子:

`

private void MapRoutes(IApplicationBuilder app, SiteSettings siteSettings)
        {
            //Custom routing
            app.UseEndpoints(routes =>
            {
                routes.MapControllerRoute(
                    name: "URLRedirection",
                    pattern: "{bitcode}",
                    defaults: new { controller = "URL", action = "RedirectShortURL" }
                );
                routes.MapControllerRoute(
                    name: "GetAllURLs",
                    pattern: "api/{controller=URL}",
                    defaults: new { controller = "URL", action = "GetAllURLs" }
                );
            });
        }

`

【问题讨论】:

  • 问号是必需的还是只是路线的正常部分?

标签: c# url asp.net-core-webapi query-string asp.net-core-3.1


【解决方案1】:

您可以使用所有控制器都可用的 HttpRequest 对象。

像这样:

[Route("")]
public IActionResult RedirectShortURL()
{
    var query = this.Request.Query;
    var queryString = this.Request.QueryString;

    // ...
}

【讨论】:

    猜你喜欢
    • 2023-01-27
    • 1970-01-01
    • 1970-01-01
    • 2015-10-20
    • 2018-05-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多