私は基本的なSitecore WebAPIルートを正常に動作させています。しかし、カスタムのSitecore WebApiルートに整数の配列を渡す必要がある場合、私は404を取得します。これはどのように行うことができますか?以下は私が試したことであり、典型的なWebApiルート(sitecoreなし)で完璧に動作します。Sitecoreのカスタムモデルバインダーを使用して、特定のWebApi経路で配列を渡す方法はありますか?
ルート
AddWebApiRoute(
name: "StudentsCourseList",
routeTemplate: "api/v1/students/courselist",
defaults: new { controller = "StudentsApi", action = "GetCourses" });
のAPIコントローラ
public class StudentsApi: ApiController
{
public async Task<IHttpActionResult> GetCourses([ModelBinder(typeof(CommaDelimitedArrayModelBinder))]long[] courseids)
{
var result = await _client.GetCourses(courseids);
if (result == null)
{
return NotFound();
}
return Ok(result);
}
}
カスタムモデルバインダー
public bool BindModel(HttpActionContext actionContext, ModelBindingContext bindingContext)
{
var key = bindingContext.ModelName;
var val = bindingContext.ValueProvider.GetValue(key);
if (val != null)
{
var s = val.AttemptedValue;
if (s != null)
{
var elementType = bindingContext.ModelType.GetElementType();
var converter = TypeDescriptor.GetConverter(elementType);
var values = Array.ConvertAll(s.Split(new[] { ","},StringSplitOptions.RemoveEmptyEntries),
x => { return converter.ConvertFromString(x != null ? x.Trim() : x); });
var typedValues = Array.CreateInstance(elementType, values.Length);
values.CopyTo(typedValues, 0);
bindingContext.Model = typedValues;
}
else
{
// change this line to null if you prefer nulls to empty arrays
bindingContext.Model = Array.CreateInstance(bindingContext.ModelType.GetElementType(), 0);
}
return true;
}
return false;
}
そして、以下のように呼び出すようにしようと、サイトコアのルート設定の一部として行われるために必要とされているすべての不足している部分がある404
/api/v1/students/courselist?courseids=1,2,3
を返しますか?
質問を編集しました。私は基本的なルーティングを持っています。カスタムモデルバインダーを追加しようとすると、ルートが認識されません。 – plutosteel