2016-03-28 49 views
0

[FromUri]のクエリ文字列に非常に奇妙なケースがあります。 下のコードは私のモデルパラメータですMVC Web Api 2 [FromUri]パラメータのバインドとクエリ文字列が異なる

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; } 
} 

これは私のコントローラコードです。

[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)); 

} 

PagingParamのパラメータバインディングを渡す場合は、上記のコードを基にしてください。

  • 索?PAGENO = 1 &がPageSize = 10 &のOrderBy = CreatedOn

しかし、その結果、このURLである必要があり、私はそれが

  • 検索になっswashbuckleに入りますか? p.PageNo = 1 & p.PageSize = 10 & p.OrderBy = CreatedOn

PagingParamのオブジェクト名は、私がどのフィックスを発見したクエリ文字列

+0

をPagingParamsあなたが予想されるクエリ文字列を使用してアプリケーションをデバッグするとパラメータが正しく内部バインドされたかどうかを確認しようとすることができますコントローラの動作?私は彼らが正しくバインドされていれば、問題はスワッシュバクルであるかもしれないと思っています。 –

+0

@OJRaqueño私はpを追加する必要がありました。パラメータがモデルに渡されるようにします。 – Nic

答えて

0

に追加する必要があります。
IFilterOperationを上書きするために必要です。
これは最善の方法ではないかもしれませんが、私の問題を解決します。

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]; 
        } 
       } 
      } 
     } 
    } 
} 
2

それを修正するための正しい方法: [FromUri(名=は「」)] P

関連する問題