C# 自定义对象作为MapRoutes定义的控制器方法中的参数

C# 自定义对象作为MapRoutes定义的控制器方法中的参数,c#,asp.net-mvc,maproute,C#,Asp.net Mvc,Maproute,考虑以下地图路线: MapRoute( "ResultFormat", "{controller}/{action}/{id}.{resultFormat}", new { controller = "Home", action = "Index", id = 0, resultFormat = "json" } ); MapRoute( "ResultFormat", "{controller}/{action}/{id}.{resultFormat}

考虑以下地图路线:

MapRoute(
    "ResultFormat",
    "{controller}/{action}/{id}.{resultFormat}",
    new { controller = "Home", action = "Index", id = 0, resultFormat = "json" }
);
MapRoute(
    "ResultFormat",
    "{controller}/{action}/{id}.{resultFormat}",
    new {
        controller = "Home",
        action = "Index",
        id = 0,
        resultFormat = Models.ResultFormat.HTML
    }
);
它的控制器方法是:

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(
    "ResultFormat",
    "{controller}/{action}/{id}.{resultFormat}",
    new { controller = "Home", action = "Index", id = 0, resultFormat = "json" }
);
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)

IMHO响应格式是一个贯穿各领域的问题,而不是由控制器来处理。我建议你为这份工作写一封信:

[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是一个可重用的组件,您可以将其应用于其他操作。

您的伪代码将正常工作。默认ModelBinder会自动将url中的字符串转换为Models.ResultFormat enum。
但是,制作ActionFilter会更好,正如Darin Dimitrov所说。

这是我提出的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
        };
    }
}

我无法让您的示例代码正常工作。我在这里发布了一个新问题:如果你能看看你有什么特别的问题,那会很棒吗?正如您在另一个问题中建议的那样,您需要重写OnActionExecuted而不是OnResultExecuting方法,因为后者在控制器操作之前运行,并且模型将始终为
null