如何解决连接字符串设置上的ASP.NET Core EF Core重定向响应
我有一些类似下面的代码,其中基于经过身份验证的用户,我需要获取其他连接字符串。
但是,有时无法通过身份验证的用户,或者找不到连接字符串。我想捕获该异常(如下),只需清除所有其他重定向,然后将用户强制转到未经授权的页面即可。
不确定下面的设置是否正确,似乎不起作用。什么需要改变?
services.AddDbContext<DbContext>((serviceProvider,options) =>
{
var httpContext = serviceProvider.GetService<IHttpContextAccessor>().HttpContext;
if (httpContext != null)
{
System.Data.sqlClient.sqlConnection connection = null;
try
{
var userIdentity = httpContext.Request.HttpContext.User.Identity;
/* do some work here based on the user to get the appoprirate connection string and set it. */
options.UsesqlServer(connection);
}
catch (Exception ex)
{
// Exception caught as it wasn't able to find a authenticated user or the connection string wasn't found.
// want to redirect to an unauthorized page,NOT WORKING
httpContext.Response.Clear();
httpContext.Response.Redirect("/Unauthorized/",true);
return;
}
finally
{
connection?.Close();
}
}
});
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。