如何将多个参数传递给WebAPI?

时间:2016-06-16 16:59:12

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

我有以下网址:

http://localhost/api/values/100/some+string+here

在WebAPI应用ValuesController中,我有:

[HttpGet]
[Route("api/values/{p1}/{p2}")]
public HttpResponseMessage Get (string p1, string p2) {
...
}

对于来电者,它永远不会访问网络API。相反,它带有404.

知道出了什么问题吗?

1 个答案:

答案 0 :(得分:1)

您正在使用Attribute Routing in ASP.NET Web API 2。确保将web api配置为使用MapHttpAttributeRoutes进行属性路由。

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        // Attribute routing.
        config.MapHttpAttributeRoutes();

        // Convention-based routing.
        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );
    }
}

接下来确保您正确定义了控制器

public class ValuesController : ApiController {
    //GET api/values/100/some-string-here
    [HttpGet]
    [Route("api/values/{p1}/{p2}")]
    public HttpResponseMessage Get (string p1, string p2) {
    ...
    }
}

您甚至可以使用RoutePrefix

[RoutePrefix("api/values")]
public class ValuesController : ApiController {
    //GET api/values/100/some-string-here
    [HttpGet]
    [Route("{p1}/{p2}")]
    public HttpResponseMessage Get (string p1, string p2) {
    ...
    }
}

此外,如果您的示例中您希望第一个参数是整数。那么你可以使用路由约束和更新方法。

[RoutePrefix("api/values")]
public class ValuesController : ApiController {
    //GET api/values/100/some-string-here
    [HttpGet]
    [Route("{p1:int}/{p2}")]
    public HttpResponseMessage Get (int p1, string p2) {
    ...
    }
}

更新:

为值控制器创建了集成测试,并且能够确认该操作已被调用

[TestMethod]
public async Task HttpClient_Should_Get_OKStatus_From_Action_With_Multiple_Parameters() {
    var config = new HttpConfiguration();
    config.MapHttpAttributeRoutes();

    using (var server = new HttpServer(config)) {

        var client = new HttpClient(server);

        string url = "http://localhost/api/values/100/some+string+here";

        using (var response = await client.GetAsync(url)) {
            Assert.AreEqual(HttpStatusCode.OK, response.StatusCode);
        }
    }
}