简体   繁体   English

如何在同一控制器的不同路由中封装通用请求处理

[英]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.

相关问题 不同路由的同一控制器中的 AmbiguousActionException - AmbiguousActionException in same controller for different routes 如何为具有不同参数的同一Controller方法设置不同的路由? - How to set different routes for the same Controller method with different parameters? SetActualResponseType使用相同方法在同一控制器中使用不同的路由 - SetActualResponseType with same method in the same controller with different routes 将两条不同的路线映射到同一控制器动作 - Map two different routes to the same controller action 如何提取超类来封装通用代码? - How to extract a superclass to encapsulate common code? 如何正确封装对具有(几乎)相同模式的不同数据库系统的访问? - How to properly encapsulate access to different database systems having (almost) the same schema? 如何在 ASP.NET MVC 5 中设置 2 条路由指向同一个 controller - How to set 2 routes point to the same controller in ASP.NET MVC 5 如何将MonoTouch.Dialog视图封装到视图控制器中? - How do you encapsulate a MonoTouch.Dialog view into a view controller? 如何从一个普通的类中调用不同类中的同名函数? - How to call functions with the same name in different classes from a common one? 将请求重定向到其他控制器 - Redirect request to different Controller
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM