具有相同路径但具有不同复杂参数的多个路由

时间:2018-10-14 10:53:51

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

例如:

api/file/occurrence?sha256=...

[HttpGet]
[Route("api/file/")]
public async Task<IHttpActionResult> GetFileBySha256Async([FromUri] FilesBySha256RequestDTO requestDTO)
{
}

api/file/occurrence?sha256=...&from_date=..&to_date=..

[HttpGet]
[Route("api/file/")]
public async Task<IHttpActionResult> GetFileBySha256AndDateAsync([FromUri] FilesBySha256AndDateRequestDTO requestDTO)
{
}

DTO:

public class FilesBySha256RequestDTO
{             
    public string sha256 { get; set; }
}


public class FilesBySha256AndDateRequestDTO
{
    public string sha256 { get; set; }
    public DateTime? from_date { get; set; }
    public DateTime? to_date { get; set; }
}

如何完成此行为?我收到以下异常:

"ExceptionMessage": "Multiple actions were found that match the request: \r\nGetFileBySha256Async on type Cynet.Client.WebAPI.Controllers.FileController\r\nGetFileOccurrencesSha256 on type Cynet.Client.WebAPI.Controllers.FileController

1 个答案:

答案 0 :(得分:0)

由于api/file/occurrence?sha256=...&from_date=..&to_date=..api/file/occurrence?sha256=...对于框架是同一回事,因此无法区分两者之间的路由。您可以做的第一件事就是更改第二条路线,例如api/fileOnDate/。如果无法执行此操作,则可以定义第三个功能,并将其用作手动路由器,例如;

[HttpGet]
[Route("api/file/")]
public async Task<IHttpActionResult> GetFileBy([FromUri] FilesBySha256AndDateRequestDTO requestDTO)
{
    if (!requestDTO.from_date.HasValue && !requestDTO.to_date.HasValue)
    {
        return await this.GetFileBySha256Async(new FilesBySha256RequestDTO() { sha256 = requestDTO.sha256 });
    }
    else
    {
        return await this.GetFileBySha256AndDateAsync(requestDTO);
    }
}

private async Task<IHttpActionResult> GetFileBySha256Async(FilesBySha256RequestDTO requestDTO)
{            
}

private async Task<IHttpActionResult> GetFileBySha256AndDateAsync(FilesBySha256AndDateRequestDTO requestDTO)
{
}

希望有帮助。