How to use Route attribute to bind query string with web API?

喜夏-厌秋 提交于 2019-12-21 05:38:14

问题


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;
    }
}

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


回答1:


Make sure attribute routing is enabled in WebApiConfig.cs

config.MapHttpAttributeroutes();

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;
    }
}

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;
    }
}



回答2:


In Web API first route template matching happens and then the action selection process.

Your C# should be like this:

public class DefaultController : ApiController
{
    [HttpGet] 
    [Route("api/Default/{name}")]
    public string Get(string name)
    {
        return $"Hello " + name;
    }
}

Now call should be like this:

http://localhost:55539/api/Default/Get?name=rami


来源:https://stackoverflow.com/questions/42199946/how-to-use-route-attribute-to-bind-query-string-with-web-api

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!