我正在移植使用$params = $this->uri->uri_to_assoc()
的PHP / CI API,以便它可以接受具有许多组合的GET请求,例如:
有很多代码,例如:
$page = 1;
if (!empty($params['page'])) {
$page = (int)$params['page'];
}
1)具有包包的常规路由:
app.UseMvc(routes => {
routes.MapRoute(
name: "default",
template: "{controller=Properties}/{action=Search}/{*params}"
);
});
但是现在我必须解析键/值对的
params
字符串,并且无法利用模型绑定。
2)属性路由:
[HttpGet("properties/search")]
[HttpGet("properties/search/beds/{beds}")]
[HttpGet("properties/search/beds/{beds}/page/{page}")]
[HttpGet("properties/search/page/{page}/beds/{beds}")]
public IActionResult Search(int beds, double lat, double lon, int page = 1, int limit = 10) {
}
显然,将允许的搜索参数和值的每种组合都繁琐。
答案 0 :(得分:1)
My other answer是更好的选择。
$params = $this->uri->uri_to_assoc()
将URI转换为关联数组,该数组基本上是.NET Dictionary<TKey, TValue>
。我们可以在ASP.NET Core中执行类似的操作。可以说我们有以下路线。
app.UseMvc(routes => {
routes.MapRoute(
name: "properties-search",
template: "{controller=Properties}/{action=Search}/{*params}"
);
});
动作
public class PropertiesController : Controller
{
public IActionResult Search(string slug)
{
var dictionary = slug.ToDictionaryFromUriPath();
return Json(dictionary);
}
}
扩展方法
public static class UrlToAssocExtensions
{
public static Dictionary<string, string> ToDictionaryFromUriPath(this string path) {
var parts = path.Split('/');
var dictionary = new Dictionary<string, string>();
for(var i = 0; i < parts.Length; i++)
{
if(i % 2 != 0) continue;
var key = parts[i];
var value = parts[i + 1];
dictionary.Add(key, value);
}
return dictionary;
}
}
结果是一个基于URI路径的关联数组。
{
"beds": "3",
"page": "1",
"sort": "price_desc"
}
但是现在我必须解析键/值对的params字符串,并且无法利用模型绑定。
如果要为此进行模型绑定,那么我们需要更进一步。
型号
public class BedsEtCetera
{
public int Beds { get; set; }
public int Page { get; set; }
public string Sort { get; set; }
}
动作
public IActionResult Search(string slug)
{
BedsEtCetera model = slug.BindFromUriPath<BedsEtCetera>();
return Json(model);
}
其他扩展方法
public static TResult BindFromUriPath<TResult>(this string path)
{
var dictionary = path.ToDictionaryFromUriPath();
var json = JsonConvert.SerializeObject(dictionary);
return JsonConvert.DeserializeObject<TResult>(json);
}
答案 1 :(得分:1)
FromPath
值提供者您想要的是将复杂模型绑定到部分url路径。不幸的是,ASP.NET Core没有内置的FromPath
绑定器。不过,幸运的是,我们可以构建自己的。
这是一个example FromPathValueProvider
in GitHub,其结果如下:
基本上,它是绑定domain.com/controller/action/key/value/key/value/key/value
。这与FromRoute
或FromQuery
值提供者所做的不同。
FromPath
值提供程序创建这样的路线:
routes.MapRoute(
name: "properties-search",
template: "{controller=Properties}/{action=Search}/{*path}"
);
将[FromPath]
属性添加到您的操作中:
public IActionResult Search([FromPath]BedsEtCetera model)
{
return Json(model);
}
神奇的是它将*path
绑定到复杂模型:
public class BedsEtCetera
{
public int Beds { get; set; }
public int Page { get; set; }
public string Sort { get; set; }
}
FromPath
值提供程序基于FromRoute
创建一个新属性。
[AttributeUsage(AttributeTargets.Parameter | AttributeTargets.Property,
AllowMultiple = false, Inherited = true)]
public class FromPath : Attribute, IBindingSourceMetadata, IModelNameProvider
{
/// <inheritdoc />
public BindingSource BindingSource => BindingSource.Custom;
/// <inheritdoc />
public string Name { get; set; }
}
创建一个新的IValueProviderFactory
public class PathValueProviderFactory : IValueProviderFactory
{
public Task CreateValueProviderAsync(ValueProviderFactoryContext context)
{
var provider = new PathValueProvider(
BindingSource.Custom,
context.ActionContext.RouteData.Values);
context.ValueProviders.Add(provider);
return Task.CompletedTask;
}
}
基于RouteValueProvider
创建一个新的IValueProvider。
public class PathValueProvider : IValueProvider
{
public Dictionary<string, string> _values { get; }
public PathValueProvider(BindingSource bindingSource, RouteValueDictionary values)
{
if(!values.TryGetValue("path", out var path))
{
var msg = "Route value 'path' was not present in the route.";
throw new InvalidOperationException(msg);
}
_values = (path as string).ToDictionaryFromUriPath();
}
public bool ContainsPrefix(string prefix) => _values.ContainsKey(prefix);
public ValueProviderResult GetValue(string key)
{
key = key.ToLower(); // case insensitive model binding
if(!_values.TryGetValue(key, out var value)) {
return ValueProviderResult.None;
}
return new ValueProviderResult(value);
}
}
PathValueProvider
使用ToDictionaryFromUriPath
扩展方法。
public static class StringExtensions {
public static Dictionary<string, string> ToDictionaryFromUriPath(this string path) {
var parts = path.Split('/');
var dictionary = new Dictionary<string, string>();
for(var i = 0; i < parts.Length; i++)
{
if(i % 2 != 0) continue;
var key = parts[i].ToLower(); // case insensitive model binding
var value = parts[i + 1];
dictionary.Add(key, value);
}
return dictionary;
}
}
在您的Startup
类中将所有内容连接在一起。
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc()
.AddMvcOptions(options =>
options.ValueProviderFactories.Add(new PathValueProviderFactory()));
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
app.UseMvc(routes => {
routes.MapRoute(
name: "properties-search",
template: "{controller=Properties}/{action=Search}/{*path}"
);
});
}
}
答案 2 :(得分:0)
恕我直言,您是从错误的角度看待这个问题的。
创建模型:
public class FiltersViewModel
{
public int Page { get; set; } = 0;
public int ItemsPerPage { get; set; } = 20;
public string SearchString { get; set; }
public string[] Platforms { get; set; }
}
API端点:
[HttpGet]
public async Task<IActionResult> GetResults([FromRoute] ViewModels.FiltersViewModel filters)
{
// process the filters here
}
结果对象(动态)
public class ListViewModel
{
public object[] items;
public int totalCount = 0;
public int filteredCount = 0;
}