[英]How to encapsulate common request handling in different routes in same controller
In my C# MVC controller, I need to setup some object which the process of the request is required. 在我的C#MVC控制器中,我需要设置一些需要处理请求的对象。 If that object fails to setup, I need to redirect user to different link. 如果该对象无法设置,则需要将用户重定向到其他链接。
My question is I need to do that in every route of my controller, how can I do that without copy and paste code? 我的问题是我需要在控制器的每条路径中执行此操作,如何在没有复制和粘贴代码的情况下执行此操作?
public async Task<ActionResult> Route1()
{
var setupObject = InitSetup();
if (setupObject == null)
return Redirect();
if (some check fail)
return Redirect();
//process Route1 request which needs setupObject not null;
return Ok();
}
public async Task<ActionResult> Route2()
{
var setupObject = InitSetup();
if (setupObject == null)
return Redirect();
if (some check fail)
return Redirect();
//process Route2 request which needs setupObject not null;
return Ok();
}
I would like to know how i can not copy and paste this 我想知道如何无法复制和粘贴此内容
var setupObject = InitSetup();
if (setupObject == null)
return Redirect();
if (some check fail)
return Redirect();
If you want to execute some code prior to executing every action in your controller then you can override the OnActionExecuting method in your controller or in your base controller (if you have any) 如果要在执行控制器中的每个动作之前执行一些代码,则可以在控制器或基本控制器(如果有)中覆盖OnActionExecuting方法。
https://msdn.microsoft.com/en-us/library/system.web.mvc.controller.onactionexecuting(v=vs.118).aspx https://msdn.microsoft.com/zh-CN/library/system.web.mvc.controller.onactionexecuting(v=vs.118).aspx
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.