我的中间件类位于不同的类库项目中,控制器位于不同的项目中。我正在尝试做的事情是,如果不满足特定条件,则从中间件重定向到自定义控制器/操作方法。
但是,我无法使用 Response.Redirect 方法来做到这一点。
我怎样才能在中间件类中做到这一点?
对此有任何帮助表示赞赏!
Rohit
这是检查请求并重定向的中间件。它可以与内联中间件或中间件类一起使用。
public void Configure(IApplicationBuilder app)
{
// use inline middleware
app.Use(async (context, next) =>
{
// if specific condition does not meet
if (context.Request.Path.ToString().Equals("/foo"))
{
context.Response.Redirect("path/to/controller/action");
}
else
{
await next.Invoke();
}
});
// or use a middleware class
app.UseMiddleware<RedirectMiddleware>();
app.UseMvc();
}
这是中间件类。
public class RedirectMiddleware
{
private readonly RequestDelegate _next;
public RedirectMiddleware(RequestDelegate next)
{
_next = next;
}
public async Task Invoke(HttpContext context)
{
// if specific condition does not meet
if (context.Request.Path.ToString().Equals("/bar"))
{
context.Response.Redirect("path/to/controller/action");
}
else
{
await _next.Invoke(context);
}
}
}
See 文档 » 基础知识 » 中间件 https://docs.asp.net/en/latest/fundamentals/middleware.html#writing-middleware了解更多信息。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)