2

これが何かにアプローチする正しい方法かどうかはわかりませんが、そうなることを望んでいます。以下の例は重いコントローラーであり、絶対に間違ったアプローチですが、それは私が探しているもののアイデアを取得します。

public class PeopleController : Controller
{
    public ActionResult List(string? api)
    {
        MyViewModel Model = new MyViewModel();

        if (api == "json") {

            // I'd like to return the Model as JSON

        } else if (api == "XML") {

            // I'd like to return the Model as XML

        } else {

            return View(Model);
        }
    }
}

今、私ができる必要があるのは、モデルが次のように要求されている場合、モデルをビューに戻すことです。

http://example.com/People/List

しかし、次のように要求された場合は、JSONを出力したいと思います。

http://example.com/People/List/?api=json

または、次のように要求された場合はXMLを出力します。

http://example.com/People/List/?api=xml

これはまったく間違っていますか?そうでない場合、これを達成するための最良のアプローチは何ですか?

MultiPurposeResult私は、すべてのフィルタリングを実行して、このように返すことができるカスタムでそれを達成することを考えていました

public class PeopleController : Controller
{
    public MultiPurposeResult List(string? api)
    {
        MyViewModel Model = new MyViewModel();
        return MultiPurpose(Model);      }
    }
}
4

2 に答える 2

5

@Mattに同意します。応答タイプを明示的に要求するのではなく、要求のcontentTypeから推測します。これは、よりRESTfulです。

たとえば、必要な応答タイプをカプセル化するための基本的な列挙型を作成しました。

public enum RestfulResultType
{
   Json,
   Html,
   Xml
}

次に、コンテンツタイプに応じて、アクションでこのプロパティを設定するカスタムモデルバインダーを作成します。

次に、コントローラーは次のようになります。

public ActionResult List(RestfulResultType resultType)
{
   var data = repo.GetSomeData();

   switch (resultType)
   {
      case RestfulResultType.Json:
         return Json(data);
      case RestfulResultType.Xml:
         return XmlResult(data); // MvcContrib
      case RestfulResultType.Html:
         return View(data);
   }
}

If you need any more customization than the regular helpers provide, then create custom ActionResult's.

You can leave the return type as ActionResult - that's the point, so that the controller can return different formats.

ResfulResultTypeModelBinder.cs:

public class ResfulResultTypeModelBinder: IModelBinder
{
   public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
   {
     if (controllerContext.HttpContext.Request.ContentType == "application/json")
        return RestfulResultType.Json;
     // other formats, etc.
   }
}

Global.asax:

ModelBinders.Binders.Add(typeof(RestfulResultType), new RestfulResultTypeModelBinder());
于 2011-09-30T01:29:10.853 に答える
1

カスタムMultiPurposeResultを作成することはできますが、私は個人的string? apiにメソッドシグネチャからを失います。代わりに、MultiPurposeに存在を確認させてRequest["format"]から、結果を出力できる形式を決定します。形式には必ずしも何も含まれていないためです。 ActionResultと関係がありますが、応答の形式はもっと重要です。

于 2011-09-30T00:17:56.400 に答える