亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

使用日期格式的路由參數驗證

使用日期格式的路由參數驗證

C#
搖曳的薔薇 2023-07-09 17:50:29
我收到所有輸入的驗證失敗消息(狀態代碼 400),當我將日期格式更改為字符串時,正則表達式有效,但 DateType 驗證不起作用。它接受 2019-02-31 作為有效輸入。知道如何使其工作 DateTime 參數類型嗎?    [HttpGet("{date}")]    public ActionResult<string> Get( [RegularExpression(@"^[0-9]{4}-[0-9]{2}-[0-9]{2}$"), DataType(DataType.Date)] DateTime date)    {         return Ok();    }
查看完整描述

3 回答

?
www說

TA貢獻1775條經驗 獲得超8個贊

對于路由驗證,您應該避免使用 for?input validation。

不要對輸入驗證使用約束。如果約束用于輸入驗證,則無效輸入會導致 404 - Not Found 響應,而不是帶有相應錯誤消息的 400 - Bad Request。路線約束用于消除相似路線的歧義,而不是驗證特定路線的輸入。

如果您想通過路由約束檢查輸入,您可以通過實現IRouteConstraint.

DateRouteConstraint


public class DateRouteConstraint : IRouteConstraint

{

? ? public static string DateRouteConstraintName = "DateRouteConstraint";

? ? public bool Match(HttpContext httpContext, IRouter route, string routeKey, RouteValueDictionary values, RouteDirection routeDirection)

? ? {

? ? ? ? object dateValue;

? ? ? ? if (values.TryGetValue("date", out dateValue))

? ? ? ? {

? ? ? ? ? ? DateTime date;

? ? ? ? ? ? string[] formats = { "yyyy-MM-dd" };

? ? ? ? ? ? if (DateTime.TryParseExact(dateValue.ToString(), formats,

? ? ? ? ? ? ? ? ? ? ? ? ? ? CultureInfo.InvariantCulture,

? ? ? ? ? ? ? ? ? ? ? ? ? ? DateTimeStyles.None, out date))

? ? ? ? ? ? {


? ? ? ? ? ? ? ? return true;

? ? ? ? ? ? }

? ? ? ? }

? ? ? ? return false;

? ? }

}

登記DateRouteConstraint


services.AddRouting(options =>

{

? ? options.ConstraintMap.Add(DateRouteConstraint.DateRouteConstraintName, typeof(DateRouteConstraint));

});

使用案例


[HttpGet("{date:DateRouteConstraint}")]

public ActionResult<string> Get(DateTime date)

{

? ? return Ok();

}


查看完整回答
反對 回復 2023-07-09
?
鳳凰求蠱

TA貢獻1825條經驗 獲得超4個贊

這里有一個例子:


https://learn.microsoft.com/en-us/aspnet/web-api/overview/web-api-routing-and-actions/create-a-rest-api-with-attribute-routing#get-books-by-publication-date


使用 dotnet core 3 我必須轉義 { 和 } (使它們加倍),它很簡單:


[HttpGet("{date:datetime:regex(\\d{{4}}-\\d{{2}}-\\d{{2}})}")]

public WeatherForecast GetForecast(DateTime date)

...


查看完整回答
反對 回復 2023-07-09
?
繁星coding

TA貢獻1797條經驗 獲得超4個贊

您不能將RegularExpression屬性應用于 a DateTime,因為它不是字符串;該屬性僅對字符串有效。

可以使用正則表達式路由約束,即[HttpGet("{date:regex(...)}")],但在這種情況下,您最好使用約束datetime[HttpGet("{date:datetime}")]。


查看完整回答
反對 回復 2023-07-09
  • 3 回答
  • 0 關注
  • 187 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號