路由以允许来自查询字符串和默认{id}模板的参数 [英] Route to allow a parameter from both query string and default {id} template

查看:97
本文介绍了路由以允许来自查询字符串和默认{id}模板的参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在ASP.Net Core WebAPI Controller中有一个操作,该操作带有一个参数.我正在尝试将其配置为能够以以下形式调用它:

I have an action in my ASP.Net Core WebAPI Controller which takes one parameter. I'm trying to configure it to be able to call it in following forms:

api/{controller}/{action}/{id}
api/{controller}/{action}?id={id}

我似乎无法正确地进行路由,因为我只能识别一种形式. (简化的)动作签名如下所示:public ActionResult<string> Get(Guid id).这些是我尝试过的路线:

I can't seem to get the routing right, as I can only make one form to be recognized. The (simplified) action signature looks like this: public ActionResult<string> Get(Guid id). These are the routes I've tried:

  • [HttpGet("Get")]-映射到api/MyController/Get?id=...
  • [HttpGet("Get/{id}")]-映射到api/MyController/Get/...
  • 它们都
  • 都映射到api/MyController/Get/...
  • [HttpGet("Get")] -- mapped to api/MyController/Get?id=...
  • [HttpGet("Get/{id}")] -- mapped to api/MyController/Get/...
  • both of them -- mapped to api/MyController/Get/...

如何配置要使用这两种URL形式调用的操作?

How can I configure my action to be called using both URL forms?

推荐答案

如果要使用路由模板 您可以在Startup.cs这样的配置方法中提供一个:

if you want to use route templates you can provide one in Startup.cs Configure Method Like This:

app.UseMvc(o =>
        {
            o.MapRoute("main", "{controller}/{action}/{id?}");
        });

现在您可以使用两个请求地址.

now you can use both of request addresses.

如果要使用属性路由,可以使用相同的方法:

If you want to use the attribute routing you can use the same way:

[HttpGet("Get/{id?}")]
public async ValueTask<IActionResult> Get(
         Guid id)
    {

        return Ok(id);
    }

这篇关于路由以允许来自查询字符串和默认{id}模板的参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆