且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何使用Route属性将查询字符串与Web API绑定?

更新时间:2023-11-07 23:50:52

确保在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;
    }
}