2

我需要在我的请求中将参数设置为不需要。

我试过了:

 @Get(value = "/list/{username}")
 HttpResponse<?> list(String username, @QueryValue(value = "actionCode") String actionCode) {
     ...
 }

当我发送请求http://localhost:8080/notification/list/00000000000时,会引发以下错误:

{
    "message": "Required Parameter [actionCode] not specified",
    "path": "/actionCode",
    "_links": {
        "self": {
            "href": "/notification/list/00000000000",
            "templated": false
        }
    }
}
4

1 回答 1

5

您可以通过javax.annotation.Nullable注释将 Micronaut 中的查询参数定义为可选:

import io.micronaut.http.annotation.Controller;
import io.micronaut.http.annotation.Get;
import io.micronaut.http.annotation.QueryValue;
import javax.annotation.Nullable;

@Controller("/sample")
public class SampleController {
    @Get("/list/{username}")
    public String list(
        String username,
        @Nullable @QueryValue String actionCode
    ) {
        return String.format("Test with username = '%s', actionCode = '%s'", username, actionCode);
    }
}

这是带有结果的示例调用。调用没有actionCode

$ curl http://localhost:8080/sample/list/some-user
Test with username = 'some-user', actionCode = 'null'

调用actionCode

$ curl http://localhost:8080/sample/list/some-user?actionCode=some-code
Test with username = 'some-user', actionCode = 'some-code'

如您所见,没有错误,它在 Micronaut 版本 1 和版本 2 中都以这种方式工作。

于 2020-10-01T05:35:49.283 回答