【问题标题】:How to call three get methods in one controller?如何在一个控制器中调用三个 get 方法?
【发布时间】:2017-02-25 05:58:09
【问题描述】:

您好,我正在开发 webapi 应用程序,我在一个控制器中有三个 GET 方法。我可以调用 2 种方法,但我无法调用第三种方法。

以下是我可以调用的方法。

[HttpGet]
[Route("me")]
public HttpResponseMessage me()
{
    return Request.CreateResponse(HttpStatusCode.OK, "Get me");
}
URL:http://localhost:22045/api/user/me

[HttpGet]
public HttpResponseMessage getUser(int id)
{
    return Request.CreateResponse(HttpStatusCode.OK, "Get user");
}

URL: http://localhost:22045/api/user/1

我无法拨打以下电话。

[Route("user/{role}")]
public HttpResponseMessage Get(string role)
{
    return Request.CreateResponse(HttpStatusCode.OK, "Get me on role");
}

我想这样称呼它

http://localhost:22045/api/user/OptionalRoleParameter

我可以在这里得到一些帮助吗?任何帮助将不胜感激。

【问题讨论】:

    标签: c# asp.net-web-api asp.net-mvc-5 asp.net-web-api-routing


    【解决方案1】:

    可选路由参数string

    [Route("user/{role?}")]
    public HttpResponseMessage Get(string role)
    {
        return Request.CreateResponse(HttpStatusCode.OK, "Get me on role");
    }
    

    您不能将 string 作为可选参数,因为 Web API 不支持将其作为可为空的约束,请参阅Route Constraints in Web API

    了解更多信息

    【讨论】:

    • 谢谢。有没有其他方法可以解决这个问题?
    • 您可以编写自定义路由约束。我在答案中给出的链接中有一个示例
    【解决方案2】:

    使用带有路由约束的属性路由应该有助于区分路由以避免冲突

    首先确保属性路由是开启的。

    config.MapHttpAttributeRoutes();
    

    然后确保控制器具有必要的属性

    [RoutePrefix("api/user")]
    public class UsersController : ApiController {
    
        //GET api/user/me
        [HttpGet]
        [Route("me")]
        public HttpResponseMessage me() {
            return Request.CreateResponse(HttpStatusCode.OK, "Get me");
        }
    
        //GET api/user/1
        [HttpGet]
        [Route("{id:int")] // NOTE the parameter constraint
        public HttpResponseMessage getUser(int id) {
            return Request.CreateResponse(HttpStatusCode.OK, "Get user");
        }   
    
        //GET api/user
        //GET api/user/OptionalRoleHere
        [HttpGet]
        [Route("{role?}")] //NOTE the question mark used to identify optional parameter
        public HttpResponseMessage Get(string role = null) {
            return Request.CreateResponse(HttpStatusCode.OK, "Get me on role");
        }
    }
    

    来源:Attribute Routing in ASP.NET Web API 2 : Route Constraints

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-05-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多