我收到了在 .NET 應用程式中創建新 REST API 的請求,但我不知道如何實作其中一個引數。
我得到了一個 Swagger 定義,引數定義如下:

如果它只是eventCreatedDateTime=2021-04-01T14:12:56 01:00沒問題,但它得到冒號和等號之間的部分,我不知道如何得到。
基本上,我可以eventCreatedDateTime:gte=2021-04-01T14:12:56 01:00作為查詢字串引數獲取,并且我必須閱讀該gte部分并且還能夠驗證它是否是允許的后綴之一。后綴不是強制性的,因此也eventCreatedDateTime=2021-04-01T14:12:56 01:00應該有效。
為了澄清起見,這是一個查詢字串引數,因此是 URL 的一部分。例如https://example.com/api/mycontroller?param1=value¶m2=value&eventCreatedDateTime:gte=2021-04-01T14:12:56 01:00¶m4=value
知道如何在 .NET 中做到這一點嗎?
uj5u.com熱心網友回復:
為此,我將使用自定義型別,例如:
public class EventCreatedDateTime
{
public string Operator { get; set; }
public string Value { get; set; }
}
接下來我將創建一個自定義模型系結器:
public class EventCreatedDateTimeModelBinderProvider : IModelBinderProvider
{
public IModelBinder GetBinder(ModelBinderProviderContext context)
{
if(context.Metadata.ModelType == typeof(EventCreatedDateTime))
{
return new EventCreatedDateTimeModelBinder();
}
return null;
}
}
public class EventCreatedDateTimeModelBinder : IModelBinder
{
public Task BindModelAsync(ModelBindingContext bindingContext)
{
foreach(var kvp in bindingContext.HttpContext.Request.Query)
{
if (kvp.Key.StartsWith("eventCreatedDateTime:"))
{
bindingContext.Result = ModelBindingResult.Success(
new EventCreatedDateTime {
Operator = kvp.Key.Substring("eventCreatedDateTime:".Length),
Value = kvp.Value.First()
});
}
}
return Task.CompletedTask;
}
}
我在 Startup 中添加的:
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers(options =>
options.ModelBinderProviders.Insert(0, new EventCreatedDateTimeModelBinderProvider())
);
...
}
}
然后動作是:
[HttpGet]
public IActionResult Get(
string param1,
string param2,
EventCreatedDateTime eventCreatedDateTime)
{...}
uj5u.com熱心網友回復:
請參閱 vernou 對 .NET Core 方法的回應。我的環境仍然是框架,所以這是解決方案。
我的自定義型別有點不同,有一個 DateTime 和一個 enumerator 屬性,這當然也可以在 Core 中使用:
public enum Operator
{
Equals,
GreaterThenEquals,
GreaterThen,
LesserThenEquals,
LesserThen
}
public class DateTimeFilter
{
public DateTime? Date { get; set; }
public Operator Operator { get; set; }
}
自定義模型系結器在框架中有點不同:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Http;
using System.Web.Http.Controllers;
using System.Web.Http.ModelBinding;
using System.Web.Http.ModelBinding.Binders;
namespace CustomModelBinders
{
public class DateTimeFilterModelBinderProvider : ModelBinderProvider
{
private CollectionModelBinderProvider originalProvider = null;
public DateTimeFilterModelBinderProvider(CollectionModelBinderProvider originalProvider)
{
this.originalProvider = originalProvider;
}
public override IModelBinder GetBinder(HttpConfiguration configuration, Type modelType)
{
IModelBinder originalBinder = originalProvider.GetBinder(configuration, modelType);
if (originalBinder != null && modelType == typeof(DateTimeFilter))
{
return new DateTimeFilterModelBinder();
}
return null;
}
}
public class DateTimeFilterModelBinder : IModelBinder
{
public bool BindModel(HttpActionContext actionContext, ModelBindingContext bindingContext)
{
if (bindingContext.ModelType != typeof(DateTimeFilter))
{
return false;
}
//Get's the correct key/value from the querystring based on your receiving paramter name.
//note: you can't use [FromUri(Name = "customName")] with the custom binder so the have to match (partially)
var query = actionContext.Request.Properties["MS_QueryNameValuePairs"] as ICollection<KeyValuePair<string, string>>;
KeyValuePair<string, string> kvp = query.First(q => q.Key.Contains(bindingContext.ModelName));
if (kvp.Key.Contains(":"))
{
bindingContext.Model =
new DateTimeFilter
{
Operator = ConvertOperator(kvp.Key.Substring(kvp.Key.IndexOf(":") 1)),
Date = ConvertDate(kvp.Value)
};
}
else
{
bindingContext.Model =
new DateTimeFilter
{
Operator = Operator.Equals,
Date = ConvertDate(kvp.Value)
};
}
return true;
}
private DateTime? ConvertDate(string str)
{
DateTime result;
DateTimeOffset resultOffset;
if (DateTime.TryParse(str, out result))
return result;
//Apparently the gets converted into a space, so we need to revert that to have a valid offset
else if (DateTimeOffset.TryParse(str.Replace(' ', ' '), out resultOffset))
return resultOffset.ToLocalTime().DateTime;
else
return null;
}
private Operator ConvertOperator(string str)
{
switch (str.ToLowerInvariant())
{
case "gte": return Operator.GreaterThenEquals;
case "gt": return Operator.GreaterThen;
case "lte": return Operator.LesserThenEquals;
case "lt": return Operator.LesserThen;
case "eq": return Operator.Equals;
default: throw new ArgumentException("Invalid operator");
}
}
}
}
The Conversion methods are perfectly fine to usein a Core application
No startup in Framework, the parameter has to be coupled to the binder with an atrbute:
[HttpGet]
public IHttpActionResult Get(string param1 = null, string param2 = null, [ModelBinder(typeof(DateTimeFilterModelBinder))] DateTimeFilter eventCreatedDateTime = null, string param3 = null)
{
//Do Logic
}
The above works as expected for eventCreatedDateTime=2021-04-01T14:12:56 01:00

And for example eventCreatedDateTime:gte=2021-04-01T14:12:56 01:00

轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/359662.html
標籤:C# 。网 休息 asp.net-web-api
