对于我的ASP.NET MVC应用程序,我正在使用ADFS身份验证。它以下列方式设置
app.UseWsFederationAuthentication(
new WsFederationAuthenticationOptions
{
MetadataAddress = ConfigurationManager.AppSettings.Get("MetadataAddress"),
Wtrealm = ConfigurationManager.AppSettings.Get("Realm"),
});
由于我无法控制的某些内容,有时MetadataAddress上的元数据无法访问。在这种情况下,我想将用户重定向到自定义视图而不是默认错误视图。如何实现这一目标?
我最终做的是创建Owin中间件,捕获由无效元数据抛出的错误,如下所示,并将用户重定向到描述问题的路由:
public class LoggingMiddleware : OwinMiddleware
{
public LoggingMiddleware(OwinMiddleware next)
: base(next)
{
}
public async override Task Invoke(IOwinContext context)
{
try
{
await Next.Invoke(context);
} catch(Exception e)
{
Logger.Error($"Encountered error in authenticating {e.ToString()}");
if(e.Source.Equals("Microsoft.IdentityModel.Protocols"))
{
context.Response.Redirect("/Home/OwinError");
} else
{
throw e;
}
}
}
}
可以使用以下行将中间件简单地添加到startup.cs文件中:
app.Use(typeof(LoggingMiddleware));