带有查询字符串的 c# webapi

c# webapi with query string

我有基于 WebApi 的 Web 服务,例如:

public class ControllerName : ApiController
{
    [Route("api/ControllerName/{p1}/{p2}/{p3}/{p4}/{p5}")]
    public string GetItemByNameAndId(string p1, string p2, string p3, string p4, string p5)
    {

    }
}

此类型请求有效:

host/api/ControllerName/1/2/3/4/5

但我想要这种类型的请求:

host/api/ControllerName/&p1=1&p2=2&p3=3&p4=4&p5=5

我收到如下错误:

A potentially dangerous Request.Path value was detected from the client (&). Which steps must be followed? Any changes in config files, any attributes etc.

感谢您的宝贵时间。

如果您不想要第一种请求

host/api/ControllerName/1/2/3/4/5

然后从路线模板中删除它们

[RoutePrefix("api/ControllerName")]
public class ControllerName : ApiController {
    //GET api/ControllerName?p1=1&p2=2&p3=3&p4=4&p5=5
    [HttpGet]
    [Route("")]
    public IHttpActionResult GetItemByNameAndId(string p1, string p2, string p3, string p4, string p5) {
        //...
        return Ok(someResult);
    }
}

这样查询字符串版本将映射到控制器操作。

参数太多不是好的设计,可以refact成一个参数class.

public class ParamClass {
    public string P1 { get; set; }
    public string P2 { get; set; }
    public string P3 { get; set; }
    public string P4 { get; set; }
    public string P5 { get; set; }
}

在你的 api 控制器中,像这样使用它:

//GET api/ControllerName?host/api/ControllerName?p1=1&p2=2&p3=3&p4=4&p5=5
[HttpGet]
[Route("")]
public IHttpActionResult GetItemByNameAndId([FromUri(PreFix="")] ParamClass param) {
    //...
    return Ok(someResult);
}