C#ASP.NET WebApi路由模板不使用uri参数

时间:2016-07-19 12:07:43

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

我有一个带有以下控制器和路由的ASP.NET WebAPI应用程序:

WebApiConfig.cs

var constraintResolver = new DefaultInlineConstraintResolver();
constraintResolver.ConstraintMap.Add("validDate", typeof(DateConstraint));

Controller.cs

[HttpGet]
[Route("deleted/{from:validDate?}/{to:validDate?}", Name = "GetDeletedData")]
[SwaggerResponse(HttpStatusCode.OK, Type = typeof(IEnumerable<SimpleClass>), Description = "response")]
public async Task<HttpResponseMessage> Get(
    [FromUri]string from = "",
    [FromUri]string to = ""
    )
{

}

约束

public class DateConstraint : IHttpRouteConstraint
{
    public bool Match(
        HttpRequestMessage request, 
        IHttpRoute route, 
        string parameterName, 
        IDictionary<string, object> values,
        HttpRouteDirection routeDirection
        )
    {
        object value;

        if (!values.TryGetValue(parameterName, out value))
            return false;

        var attribute = new DateAttribute();

        return attribute.IsValid(value);
    }
}

即使我传递了以下网址,上面的路线也会被击中,即我没有从参数传递到参数,但控制器被击中,没有任何反应。

http://localhost:65190/products/deleted?adfear=2016-07-01 03:30:05&adfaewr=2016-07-01 03:30:05

如何确保只有在传递了正确的参数时才会命中路径,否则会抛出404找不到错误?

3 个答案:

答案 0 :(得分:3)

为什么重新发明轮子。

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

已存在datetime约束。

你还能做的就是让最后一个日期成为可选项,这样如果提供了一个日期,它将使用从日期到当前日期进行过滤。

[HttpGet]
[Route("deleted/{from:datetime}/{to:datetime?}", Name = "GetDeletedData")]
[SwaggerResponse(HttpStatusCode.OK, Type = typeof(IEnumerable<SimpleClass>), Description = "response")]
public async Task<HttpResponseMessage> Get(DateTime from, DateTime? to = null)
{
    //....
}

根据您的评论,您可以执行类似的操作

//GET products/deleted
[HttpGet]
[Route("deleted")]
public async Task<HttpResponseMessage> Get() {
    //...
}

//GET products/deleted/2016-01-01
//GET products/deleted/2016-01-01/2016-03-31
[HttpGet]
[Route("deleted/{from:datetime}/{to:datetime?}", Name = "GetDeletedData")]
public async Task<HttpResponseMessage> Get(DateTime from, DateTime? to = null) {
    //...
}

现在应该处理这三种情况

//GET products/deleted
//GET products/deleted/{from}
//GET products/deleted/{from}/{to}

<强>更新

如果两个参数都是模式可选

//GET products/deleted - including query string will hit this
//GET products/deleted?adfear=2016-07-01 03:30:05&adfaewr=2016-07-01 03:30:05
//GET products/deleted/2016-01-01
//GET products/deleted/2016-01-01/2016-03-31
[HttpGet]
[Route("deleted/{from:datetime?}/{to:datetime?}", Name = "GetDeletedData")]
public async Task<HttpResponseMessage> Get(DateTime? from = null, DateTime? to = null) {
    //...
}

<强> UPDATE2

基于对话

您可以创建过滤器模型

public class DateRangeFilter {
    public DateTime? from { get; set; }
    public DateTime? to { get; set; }
}

你可以在行动中使用它。

// GET products/deleted
// GET products/deleted?from=2016-01-01&to=2016-03-31
[HttpGet]
[Route("deleted", Name = "GetDeletedData")]
public async Task<HttpResponseMessage> Get([FromUri]DateRangeFilter filter) {
    //...
}

还要记住通过过滤器或在操作中进行模型验证。

答案 1 :(得分:2)

您可以简单地制作所需的参数(问号表示thery是可选的)

[HttpGet]
[Route("deleted/{from:validDate}/{to:validDate}", Name = "GetDeletedData")]
[SwaggerResponse(HttpStatusCode.OK, Type = typeof(IEnumerable<SimpleClass>), Description = "response")]
public async Task<HttpResponseMessage> Get(
    [FromUri]string from = "",
    [FromUri]string to = ""
    )
{

}

答案 2 :(得分:1)

您必须省略约束上的问号以及参数的默认值:

[HttpGet]
[Route("deleted/{from:validDate}/{to:validDate}", Name = "GetDeletedData")]
[SwaggerResponse(HttpStatusCode.OK, Type = typeof(IEnumerable<SimpleClass>), Description = "response")]
public async Task<HttpResponseMessage> Get(
    [FromUri]string from,
    [FromUri]string to
    )
{

}