如何解决如何从 OnActionExecution 重定向到控制器中的 ActionAsp.net core 5
大家好,我正在做一个针对 .intel_Syntax noprefix
.data
message: .asciz "Hello World!\n"
.text
.global main
main:
lea rdi,message
call printf
ret
的 Asp.net core
项目
我创建了一个继承自 .Net 5
的类,并使用了 IActionFilter
方法,我在其中做了一些逻辑,并希望从它重定向到 OnActionExecution
中的另一个 Action
。
问题:
问题是我如何重定向到 Controller
来自的操作,我根据我的知识尝试了很多解决方案,但没有一个成功。
我尝试了什么:
request
问题: 我有两个问题,
- 如何知道请求来自的
public class ValidationFilterattribute : IActionFilter { public void OnActionExecuting(ActionExecutingContext context) { //some logic to get the model if(!context.ModelState.IsValid) { Context.Result = new RedirectToAction(“Idon’t kNow how to get action”,“I don’t kNow how to get controller”,new{model= /*model I got*/}); } } public void OnActionExecuted(ActionExecutedContext context) { } }
和Action
名称? - 如何重定向到同一个
Controller
但在同一个Action
中并发送在“OnActionExecution”中获得的相同模型
我为什么要这样做:
我的想法是使用我自己的“IActionFilter”类和 Controller
中工作的任何方法来检查发送的 HttpPost
是否有效,如果无效则 model
方法将添加 {{1 }} 到 OnActionExecution
并再次将其发送到操作中。
请帮忙解决这个问题?
解决方法
你可以像这样定义一个自定义的 ActionFilter
public class ValidationFilterAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
var controllerName = filterContext.ActionDescriptor.ControllerDescriptor.ControllerName; // Get controller name
var modelState = (filterContext.Controller. as Controller).ViewData.ModelState; // Get the model state of the request
var model = (filterContext.Controller as Controller).ViewData.Model; // Get the model of the request
//do your stuff here
base.OnActionExecuting(filterContext);
}
}
然后注册您的过滤器,以便将其应用于您项目中的每个控制器和每个操作
public void ConfigureServices(IServiceCollection services)
{
services.AddMvcCore(options =>
{
options.Filters.Add(typeof(ValidationFilterAttribute));
});
}
这样,在点击控制器的操作方法主体之前,每个请求都会通过您的 ValidationFilterAttribute
,您可以在其中检查他的 Model
并更改他的 ModelState
。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。