属性处理ASP.NET Web API可选参数路由 [英] Attribute routing with optional parameters in ASP.NET Web API
问题描述
我想使用的Web API 2属性的路由设置一个自定义的API。我有我的工作路线,这样我的函数被调用,但由于某种原因,我需要在我的第一个参数传递的一切才能正常工作。以下是我的URL要支持:
的http:// mysite的/ API /服务名称/参数1
HTTP:// mysite的/ API /服务名称/参数1参数=值
?HTTP:// mysite的/ API /服务名称/参数1参数=值2和放大器;参数3 = VALUE3
?HTTP:// mysite的/ API /服务名称/参数1参数=值2和放大器;参数3 =值3&安培; P4 = V4
最后3个URL工作,但第一个说不采取行动是在控制器的控制器名称与请求匹配上找到的。
我的控制器看起来是这样的:
公共类MyServiceController:ApiController
{
[路线(API /服务名称/ {参数1})]
[HTTPGET]
公共异步任务<返回类型>获取(字符串参数1,日期时间?参数2,字符串参数3 =,字符串P4 =)
{
//过程
}
}
网页API要求即使是空类型明确设置可选值...所以你可以尝试设置下面,你会看到你的第一次成功的请求。
日期时间?参数2 = NULL
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¶meter3=value3
http://mysite/api/servicename/parameter1?parameter2=value2¶meter3=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 requires to explicitly set optional values even for nullable types...so you can try setting the following and you should see your 1st request succeed
DateTime? parameter2 = null
这篇关于属性处理ASP.NET Web API可选参数路由的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!