如何使用Route属性将查询字符串与Web API绑定? [英] How to use Route attribute to bind query string with web API?
问题描述
我正在尝试使它起作用:
I'm trying to get this to work:
[Route("api/Default")]
public class DefaultController : ApiController
{
[HttpGet, Route("{name}")]
public string Get(string name)
{
return $"Hello " + name;
}
}
通过调用此http://localhost:55539/api/Default?name=rami
但不起作用,也尝试了此操作:http://localhost:55539/api/Default/Hello?name=rami
,这也没有起作用:http://localhost:55539/api/Default/Hello/rami
by calling this http://localhost:55539/api/Default?name=rami
but not working, tried this also:http://localhost:55539/api/Default/Hello?name=rami
, Also this not working: http://localhost:55539/api/Default/Hello/rami
推荐答案
确保在WebApiConfig.cs中启用了属性路由
Make sure attribute routing is enabled in WebApiConfig.cs
config.MapHttpAttributeroutes();
ApiController动作可以分配多个路由.
ApiController actions can have multiple routes assigned to them.
[RoutePrefix("api/Default")]
public class DefaultController : ApiController {
[HttpGet]
//GET api/Default
//GET api/Default?name=John%20Doe
[Route("")]
//GET api/Default/John%20Doe
[Route("{name}")]
public string Get(string name) {
return $"Hello " + name;
}
}
还可以选择将该参数设置为可选参数,然后允许您在不使用内联参数的情况下调用URL,并使路由表使用查询字符串,类似于在基于约定的路由中进行的操作.
There is also the option of making the parameter optional, which then allow you to call the URL with out the inline parameter and let the routing table use the query string similar to how it is done in convention-based routing.
[RoutePrefix("api/Default")]
public class DefaultController : ApiController {
[HttpGet]
//GET api/Default
//GET api/Default?name=John%20Doe
//GET api/Default/John%20Doe
[Route("{name?}")]
public string Get(string name = null) {
return $"Hello " + name;
}
}
这篇关于如何使用Route属性将查询字符串与Web API绑定?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!