为从查询字符串获取的值添加数据注释

时间:2013-04-30 05:14:22

标签: asp.net-mvc asp.net-mvc-4 data-annotations

我需要为下面url中提到的{ID}中的web api服务添加数据注释,以接受最大长度为7,否则我应该抛出自定义异常。我没有任何模型类可以使用maxlength属性。感谢您的帮助。

http://xyz.com/ {ID}

2 个答案:

答案 0 :(得分:0)

您可以尝试做的是以下内容,假设您在问题中的网址:

        routes.MapRoute(
            "Default", // Route name
            "{id}", // URL with parameters
            new { controller = "Home", action = "Index" }, // Parameter defaults,
            new { id = @"\d{4}" } //Constraint
        );

        routes.MapRoute(
            "DefaultError", // Route name
            "{id}", // URL with parameters
            new { controller = "Home", action = "ThrowError" }, // Parameter defaults,
            new { id = @"\d{5,}" } //Constraint
        );

并在控制器中使用ThrowError(int id)方法抛出所需的错误或重定向到错误。

答案 1 :(得分:0)

为什么不在Web API方法中包含处理程序?

public SomeModel Get(int id)
{
    if (id != null && id <= 7)
         return something();

    throw new HttpResponseException(HttpStatusCode.{BadRequest|Forbidden|SomethingElse});
}