在我的控制器中的每个操作中,我使用以下代码:
public async System.Threading.Tasks.Task<ActionResult> Details(string source, string id)
{
var max = Helpers.GetSource(source);
if (max == null)
return Content("Please check your request URL format, there is no source defined for your input");
using (var cmax = new CMax(max.ConnectionString))
{
我希望能够嵌入基本功能,默认情况下让所有操作都采用Source,并生成一个&#39; max&#39;对象以及在我的using语句中包装我的Action函数的主体。
是否可以在基类中实现此功能,以便在每个操作中都没有这个冗余代码?
答案 0 :(得分:3)
我发现最好实现此方法的方法是覆盖OnActionExecuting。
protected override void OnActionExecuting(ActionExecutingContext filterContext)
{
_max = Helpers.GetSource(Request.QueryString["source"]);
if (_max == null)
{
filterContext.Result =
Content("Please check your request URL format, there is no source defined for your input");
return;
}
base.OnActionExecuting(filterContext);
}
这允许我在Class Level而不是Action Level定义_max,并在Class Level再次实现检查逻辑。
答案 1 :(得分:1)
public class TwitterFragment extends ListFragment {
final Callback<Tweet> callback = new Callback<Tweet>() {
@Override
public void success(Result<Tweet> result) {
setListShown(true);
Toast.makeText(getActivity(), "NotFail", Toast.LENGTH_LONG).show();
}
@Override
public void failure(TwitterException e) {
Toast.makeText(getActivity(), "Fail", Toast.LENGTH_LONG).show();
}
};
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
startWork();
}
public void startWork() {
final UserTimeline userTimeline = new UserTimeline.Builder().screenName(Config.TWITTER_ACCOUNT).build();
final TweetTimelineListAdapter adapter = new TweetTimelineListAdapter.Builder(getActivity())
.setOnActionCallback(callback).setTimeline(userTimeline).setViewStyle(R.style.tw__TweetDarkStyle).build();
setListAdapter(adapter);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.twitter_layout, container, false);
}
}
然后在public class MyBaconActionFilterAttribute : ActionFilterAttribute
{
public override void OnResultExecuting(ResultExecutingContext context)
{
// Some code here
base.OnResultExecuting(filterContext);
}
}
global.asax
现在将对所有操作方法运行,而无需触摸任何控制器。
答案 2 :(得分:0)
只需创建自己的继承Controller
的基类,即控制器继承的基类。
public abstract class MyBaseController : Controller
{
protected void SomeCommonMethod()
{
....
}
}
public class HomeController : MyBaseController
{
public void Index()
{
SomeCommonMethod();
}
}