1

このMapRouteを検討してください。

MapRoute(
    "ResultFormat",
    "{controller}/{action}/{id}.{resultFormat}",
    new { controller = "Home", action = "Index", id = 0, resultFormat = "json" }
);

そしてそれはコントローラーメソッドです:

public ActionResult Index(Int32 id, String resultFormat)
{
    var dc = new Models.DataContext();

    var messages = from m in dc.Messages where m.MessageId == id select m;

    if (resultFormat == "json")
    {
        return Json(messages, JsonRequestBehavior.AllowGet); // case 2
    }
    else
    {
        return View(messages); // case 1
    }
}

これがURLシナリオです

  • Home/Index/1ケース1に進みます
  • Home/Index/1.htmlケース1に進みます
  • Home/Index/1.jsonケース2に進みます

これはうまく機能します。しかし、私は文字列をチェックするのが嫌いです。コントローラメソッドのパラメータ として使用される列挙型をどのように実装しますか? 基本的な考え方を説明するためのいくつかの擬似コード:resultFormat


namespace Models
{
    public enum ResponseType
    {
        HTML = 0,
        JSON = 1,
        Text = 2
    }
}

MapRoute:

MapRoute(
    "ResultFormat",
    "{controller}/{action}/{id}.{resultFormat}",
    new {
        controller = "Home",
        action = "Index",
        id = 0,
        resultFormat = Models.ResultFormat.HTML
    }
);

コントローラメソッドのシグネチャ:

public ActionResult Index(Int32 id, Models.ResultFormat resultFormat)
4

3 に答える 3

3

私見では、応答形式は横断的関心事であり、それを台無しにするのはコントローラーではありません。このジョブのActionFilterを作成することをお勧めします。

[AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, Inherited = true, AllowMultiple = true)]
public sealed class RespondToAttribute : ActionFilterAttribute
{
    public override void OnActionExecuted(ActionExecutedContext filterContext)
    {
        var resultFormat = filterContext.RouteData.Values["resultFormat"] as string ?? "html";
        ViewResult viewResult = filterContext.Result as ViewResult;
        if (viewResult == null)
        {
            // The controller action did not return a view, probably it redirected
            return;
        }
        var model = viewResult.ViewData.Model;
        if (string.Equals("json", resultFormat, StringComparison.OrdinalIgnoreCase))
        {
            filterContext.Result = new JsonResult { Data = model };
        }
        // TODO: you could add some other response types you would like to handle
    }
}

これにより、コントローラーのアクションが少し簡素化されます。

[RespondTo]
public ActionResult Index(int id)
{
    var messages = new string[0];
    if (id > 0)
    {
        // TODO: Fetch messages from somewhere
        messages = new[] { "message1", "message2" };
    }
    return View(messages);
}

ActionFilterは、他のアクションに適用できる再利用可能なコンポーネントです。

于 2009-11-01T10:45:12.077 に答える
0

これは私が思いついたActionFilterです:

public sealed class AlternateOutputAttribute :
                    ActionFilterAttribute, IActionFilter
{
    void IActionFilter.OnActionExecuted(ActionExecutedContext aec)
    {
        ViewResult vr = aec.Result as ViewResult;

        if (vr == null) return;

        var aof = aec.RouteData.Values["alternateOutputFormat"] as String;

        if (aof == "json") aec.Result = new JsonResult
        {
            JsonRequestBehavior = JsonRequestBehavior.AllowGet,
            Data = vr.ViewData.Model,
            ContentType = "application/json",
            ContentEncoding = Encoding.UTF8
        };
    }
}
于 2009-11-02T17:18:06.950 に答える
0

擬似コードは正しく機能します。デフォルトのModelBinderは、URLの文字列をModels.ResultFormat列挙型に自動的に変換します。しかし、Darin Dimitrovが言ったように、ActionFilterを作成する方が良いでしょう。

于 2009-11-01T16:46:03.673 に答える