简体   繁体   中英

Attribute routing with optional parameters in ASP.NET Web API

I'm trying to use Web API 2 attribute routing to set up a custom API. I've got my route working such that my function gets called, but for some reason I need to pass in my first parameter for everything to work properly. The following are the URLs I want to support:

http://mysite/api/servicename/parameter1
http://mysite/api/servicename/parameter1?parameter2=value2
http://mysite/api/servicename/parameter1?parameter2=value2&parameter3=value3
http://mysite/api/servicename/parameter1?parameter2=value2&parameter3=value3&p4=v4

The last 3 URLs work but the first one says "No action was found on the controller 'controller name' that matches the request."

My controller looks like this:

public class MyServiceController : ApiController
{
    [Route("api/servicename/{parameter1}")]
    [HttpGet]
    public async Task<ReturnType> Get(string parameter1, DateTime? parameter2, string parameter3 = "", string p4 = "")
    {
        // process
    }
}

Web API需要显式设置可选值,即使对于可以为空的类型...因此您可以尝试设置以下内容,您应该看到第一个请求成功

DateTime? parameter2 = null

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