简体   繁体   English

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

[英]C# ASP.NET WebApi route template not working with uri parameters

I have an ASP.NET WebAPI application with the following controller and route: 我有一个带有以下控制器和路由的ASP.NET WebAPI应用程序:

WebApiConfig.cs WebApiConfig.cs

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

Controller.cs 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 = ""
    )
{

}

Constraint 约束

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);
    }
}

The above route is hit even though I pass the following url ie I am not passing from and to parameters but the controller is hit and nothing happen. 即使我传递了以下网址,也击中了上述路由,即我没有从参数传递到参数,但控制器被击中,但没有任何反应。

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

How to make sure the route is hit only when the correct parameters are passed or else throw 404 not found error? 如何确保仅当传递正确的参数时才击中路线,否则抛出404 not found错误?

Why re-invent the wheel. 为什么要重新发明轮子。

Attribute Routing in ASP.NET Web API 2:Route Constraints ASP.NET Web API 2中的属性路由:路由约束

there already exists a datetime constraint. 已经存在datetime约束。

Also what you can do is just make the last date optional so that if provided a from date, it will filter using the from date to current date. 另外,您可以做的只是将最后一个日期设为可选,这样,如果提供了起始日期,它将使用起始日期到当前日期进行过滤。

[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)
{
    //....
}

Based on your comments you can do something like this 根据您的评论,您可以执行以下操作

//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) {
    //...
}

this should now handle the three cases 现在应该处理这三种情况

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

Update 更新

If both parameters are mode optional 如果两个参数均为模式可选

//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 UPDATE2

based on conversation 基于对话

you can create a filter model 您可以创建过滤器模型

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

and you can use that in your action. 您可以在行动中使用它。

// 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) {
    //...
}

Also remember to do model validation either via filter or within the action. 还记得通过过滤器或在动作中进行模型验证。

You can simply make the parameters required(question mark means thery are optional) 您只需将参数设为必需(问号表示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 = ""
    )
{

}

You have to omit the question mark on the constraints and the default values for your parameters: 您必须省略约束上的问号和参数的默认值:

[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
    )
{

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM