ApiConvention响应类型-匹配多个Get方法

时间:2019-02-22 10:41:19

标签: api asp.net-core asp.net-core-mvc asp.net-core-2.1 conventions

我的项目中有几个控制器,它们具有多个Get方法:

public async Task<ActionResult<IEnumerable<DModel>>> Get(){}
public async Task<ActionResult<DModel>> Get(int id){}

我正在尝试创建一个与之匹配但依赖于参数的约定-这样才能分辨出区别。到目前为止,我有:

        [ProducesResponseType(StatusCodes.Status200OK)]
        [ProducesResponseType(typeof(string), StatusCodes.Status400BadRequest)]
        [ProducesDefaultResponseType]
        [ApiConventionNameMatch(ApiConventionNameMatchBehavior.Prefix)]
        public static void Get()
        {
        }

        [ProducesResponseType(StatusCodes.Status200OK)]
        [ProducesResponseType(typeof(string), StatusCodes.Status400BadRequest)]
        [ProducesResponseType(StatusCodes.Status404NotFound)]
        [ApiConventionNameMatch(ApiConventionNameMatchBehavior.Prefix)]
        [ProducesDefaultResponseType]
        public static void Get(
            [ApiConventionNameMatch(ApiConventionNameMatchBehavior.Prefix)]
            int id)
        {
        }

这似乎不起作用,尝试启动API时出现错误:

  

System.ArgumentException:方法名称'Get'对于   约定类型“ P.API.Conventions.PApiConventions”。超过一个   名称为“ Get”的方法。 Arg_ParamName_Name'

这将针对启动中的app.UseMvc()显示。 我了解发生了什么,但似乎无法通过逻辑来正确解决get方法。

1 个答案:

答案 0 :(得分:1)

我不是Web API约定的专家,但是在各种测试中,我注意到这些约定不会影响路由和模型绑定。因此,您仍然需要为操作明确指定HttpMethod属性

[HttpGet]
public async Task<ActionResult<IEnumerable<DModel>>> Get(){}

//parameter name must match string inside curly braces
//if you leave {id} and update parameter name to idName
//(which matches prefix name convention)
//model binder won't bind value to parameter
//although tools that are using api conventions still will properly read controller info
[HttpGet("{id}")]
public async Task<ActionResult<DModel>> Get(int id){}