我目前正在开发 MVC.NET 3 应用程序;我最近参加了“鲍勃叔叔”马丁的一门类(class),这启发了我(让我感到羞耻?)认真审视我当前的开发实践,尤其是我的重构习惯。
所以:我的一些路线符合:
{ Controller }/{ Action }/{类型}
其中 type 通常确定要返回的 ActionResult 的类型,例如:
public class ExportController
{
public ActionResult Generate(String type, String parameters)
{
switch (type)
{
case "csv":
//do something
case "html":
//do something else
case "json":
//do yet another thing
}
}
}
有没有人成功地将“用多态替换开关”重构应用于这样的代码?这甚至是个好主意吗?很高兴听到您对这种重构的经验。
提前致谢!
最佳答案
在我看来,这个 Controller Action 正在为自定义 Action 结果而尖叫:
public class MyActionResult : ActionResult
{
public object Model { get; private set; }
public MyActionResult(object model)
{
if (model == null)
{
throw new ArgumentNullException("Haven't you heard of view models???");
}
Model = model;
}
public override void ExecuteResult(ControllerContext context)
{
// TODO: You could also use the context.HttpContext.Request.ContentType
// instead of this type route parameter
var typeValue = context.Controller.ValueProvider.GetValue("type");
var type = typeValue != null ? typeValue.AttemptedValue : null;
if (type == null)
{
throw new ArgumentNullException("Please specify a type");
}
var response = context.HttpContext.Response;
if (string.Equals("json", type, StringComparison.OrdinalIgnoreCase))
{
var serializer = new JavaScriptSerializer();
response.ContentType = "text/json";
response.Write(serializer.Serialize(Model));
}
else if (string.Equals("xml", type, StringComparison.OrdinalIgnoreCase))
{
var serializer = new XmlSerializer(Model.GetType());
response.ContentType = "text/xml";
serializer.Serialize(response.Output, Model);
}
else if (string.Equals("csv", type, StringComparison.OrdinalIgnoreCase))
{
// TODO:
}
else
{
throw new NotImplementedException(
string.Format(
"Sorry but \"{0}\" is not a supported. Try again later",
type
)
);
}
}
}
进而:
public ActionResult Generate(string parameters)
{
MyViewModel model = _repository.GetMeTheModel(parameters);
return new MyActionResult(model);
}
Controller 不应该关心如何序列化数据。这不是他的责任。 Controller 不应该做任何这样的管道。他应该专注于获取领域模型,将它们映射到 View 模型并传递这些 View 模型以查看结果。
关于asp.net-mvc-3 - 在我的 Controller 中重构 Switch 语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6749999/