简体   繁体   中英

Where/how to include params in RESTful API using MVC on GET request

I'm attempting to construct an API that adheres to REST principles as closely as possible and ran into a bit of a snag. I am attempting to GET a file in a directory on an Azure Data Lake FileSystem (container). I've constructed a RESTful URI structure for referencing resources, but I'm not sure exactly how to fit in a couple of parameters, specifically the DataLake Account Name, and the Access Key; into the request URI. Here's what I mean:

A working version of my controller looks like this (as you can see, some items are hard-coded):

    [HttpGet("api/location/{locationId}/dates/{dateId}/files/{fileId}")]
    public IActionResult GetFile(string locationId, string dateId, string fileId)
    {
        var accountName = "my-hard-coded-Account";
        var key = "my-hard-coded-Key";
        return Ok(myDataLakeClient.GetFile($"{locationId}/{dateId}/{fileId}", accountName, key);
    }

Since my service will need to talk to multiple DataLakes, I need to collect the account and key in the request, so my next version looked like this:

[HttpGet("api/location/{locationId}/dates/{dateId}/files/{fileId}?accountName={accountName}&key={key}")]
public IActionResult GetFile(string locationId, string dateId, string fileId, string accountName, string key)
{
    return Ok(myDataLakeClient.GetFile($"{locationId}/{dateId}/{fileId}", accountName, key);
}

In the second case, if I make a call to:

GET localhost4200:http://localhost:51044/api/io/solutions?accountName=myAccount&key=myKey

I'm slapped down with an error:

RoutePatternException: The literal section 'solutions?accountName=' is invalid. Literal sections cannot contain the '?' character.

I feel like I could work around this by switching over to a POST request and just including the key and account in the request body, but that doesn't really adhere to REST principles, since POST should be used for creating resources, and GET should be used for requesting resources.

You do not need to declare query string parameters as part of your route definition in the HttpGet attribute. Change it to this:

[HttpGet("api/location/{locationId}/dates/{dateId}/files/{fileId}")]

Your query string parameters will still get matched up to the action method parameters based on their names.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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