[英]MVC Web Api 2 [FromUri] parameter binding and querystring is different
I'm having a very weird case in my querystring for [FromUri]. 我在[FromUri]的查询字符串中遇到一个非常奇怪的情况。 The code below is my model parameter 下面的代码是我的模型参数
public class PagingParams
{
public PagingParams()
{
// set the default values
this.PageNo = 1;
this.PageSize = 30;
}
public int PageNo { get; set; }
public int PageSize { get; set; }
public string OrderBy { get; set; }
}
This is my controller code. 这是我的控制器代码。
[Route("search")]
[ResponseType(typeof(PagingList<EmailTemplatesInfo>))]
public async Task<IHttpActionResult> Search(SearchParams searchOption, [FromUri] PagingParams p)
{
// Check
if (searchOption == null) return BadRequest("Invalid search options");
// Filter EmailTemplate by Keyword
var emailTemplate = db.EmailTemplates.Where(et => et.Name.Contains(searchOption.Keyword) ||
et.Description.Contains(searchOption.Keyword)).ProjectTo<EmailTemplatesInfo>();
// Filter by Status
emailTemplate = emailTemplate.Where(et => searchOption.Status.Contains(et.Status));
// Check & Set
if (p == null) p = new PagingParams();
// Set Default Sort
if (string.IsNullOrEmpty(p.OrderBy)) p.OrderBy = DEFAULT_ORDERBY;
return Ok(new PagingList<EmailTemplatesInfo>(p, emailTemplate));
}
Base on the code above if i want to pass in Parameter Binding for PagingParam. 如果我想传递PagingParam的参数绑定,请基于以上代码。
Should be this url 应该是这个网址
But the result i get in swashbuckle it become 但是结果我一头雾水变成了
the object name for PagingParam need to append in the querystring PagingParam的对象名称需要附加在querystring中
修复它的正确方法:[FromUri(Name =“”)] PagingParams p
I found a fix which. 我找到了解决方法。
Required to write IFilterOperation to overwrite it.. 需要编写IFilterOperation才能覆盖它。
It might not the best way but it solve my problem. 这可能不是最好的方法,但可以解决我的问题。
public class HandleFromUriParam : IOperationFilter
{
public void Apply(Operation operation, SchemaRegistry schemaRegistry, ApiDescription apiDescription)
{
string[] splitter = null;
var fromUriParams = apiDescription.ActionDescriptor.GetParameters().
Where(param => param.GetCustomAttributes<FromUriAttribute>().Any()).ToArray();
foreach (var param in fromUriParams)
{
var fromUriAttribute = param.GetCustomAttributes<FromUriAttribute>().FirstOrDefault();
// Check
if (fromUriAttribute != null)
{
var operationParam = operation.parameters;
foreach (var item in operationParam)
{
if (item.name.Contains(param.ParameterName))
{
splitter = item.name.Split('.');
item.name = splitter[splitter.Length - 1];
}
}
}
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.