Route to allow a parameter from both query string and default {id} template

点点圈 提交于 2020-01-06 04:56:07

问题


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}

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")] -- mapped to api/MyController/Get?id=...
  • [HttpGet("Get/{id}")] -- mapped to api/MyController/Get/...
  • both of them -- mapped to api/MyController/Get/...

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


回答1:


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);
    }



回答2:


Make the parameter optional

[Route("api/MyController")]
public class MyController: Controller {

    //GET api/MyController/Get
    //GET api/MyController/Get/{285A477F-22A7-4691-AA51-08247FB93F7E}
    //GET api/MyController/Get?id={285A477F-22A7-4691-AA51-08247FB93F7E}
    [HttpGet("Get/{id:guid?}"
    public ActionResult<string> Get(Guid? id) {

        if(id == null)
            return BadRequest();

        //...
    }    
}

This however means that you would need to do some validation of the parameter in the action to account for the fact that it can be passed in as null because of the action being able to accept api/MyController/Get on its own.

Reference Routing to controller actions in ASP.NET Core



来源:https://stackoverflow.com/questions/51797617/route-to-allow-a-parameter-from-both-query-string-and-default-id-template

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!