【问题标题】:Open Specified ASP.NET MVC Views From Hyperlinks Inside Email Body从电子邮件正文中的超链接打开指定的 ASP.NET MVC 视图
【发布时间】:2017-08-29 02:43:48
【问题描述】:

我刚刚了解了 ASP.NET MVC。我有一个具有以下场景的网站:

Login -> Main Page (Index) -> Edit Page (Edit)

所以,在LoginController用户登录时,它会重定向到main page并从MainPage编辑一条记录。

每次通过 ASP.NET MVC 创建新记录时,系统都会向经理发送一封电子邮件。在电子邮件消息中,有一个超链接会将经理重定向到编辑表单。但首先,他需要登录,因为除非他登录,否则无法打开编辑表单。 例如:

http://localhost:1212/Main/Edit/ID-001

我在MainController 中添加了Authorize Attribute。但它只适用于Main Page。所以即使我还没有登录,我也可以打开Edit Page

这里是主控制器:

[Authorize]
public class MainController : Controller
{
    string connString = @"Data Source=DESKTOP-FSET3FF,1433; Initial Catalog=INOVA_Data; User Id=sa; Password=Copoe113";

    public ActionResult Index(string username)
    {
        if (Session["username"] != null)
        {
            string user = Session["username"].ToString();
            SqlConnection conn = new SqlConnection(connString);
            conn.Open();
            string sqlQuery = @"select Animals, Gender from dbo.Animals where Pemilik = @user";

            //string h = x => x.
            SqlCommand cmd = new SqlCommand(sqlQuery, conn);
            cmd.Parameters.AddWithValue("@user", user);
            DataTable dt = new DataTable();
            SqlDataAdapter da = new SqlDataAdapter(cmd);
            da.Fill(dt);
            conn.Close();
            return View(dt);
        }
        else
        {
            return RedirectToAction("Login", "Login");
        }
    }

    public ActionResult Edit()
    {
        return View();
    }
}

第二个问题,上面我写了我的网站场景,就是

Login-> MainPage (Index) -> EditPage (Edit)

基于电子邮件上的超链接,如何使应用程序重定向到 EditPage 而不重定向到 MainPage。

Login -> EditPage (Edit)

编辑第二个问题

简而言之,当用户尝试直接访问编辑视图时,应用程序会将用户重定向到登录视图。当heler登录成功时,应用程序会将用户重定向到编辑视图。

但是现在,当登录成功时,系统会将用户重定向到主视图。登录后如何让应用重定向到编辑视图?

【问题讨论】:

  • 我认为您需要显示Login控制器操作方法代码。如果在 URL 模式请求匹配 Edit 操作时使用 RedirectToAction,您可以重定向到编辑页面。
  • 我认为电子邮件超链接不包含在您的 MVC 项目中,对吗?您所需要的只是当用户从电子邮件中单击该超链接时,它将重定向到您的 mvc 项目,这里是 public ActionResult Edit()。或先登录。
  • 当您使用默认的 ASP.NET MVC 项目模板时,该功能应该已经包含在开箱即用的范围内。您可以尝试在新的隐身或私人浏览器窗口中打开电子邮件中的链接吗?
  • 1.在 Edit 方法上使用 [Authorize]。

标签: c# asp.net-mvc asp.net-mvc-4 authentication basic-authentication


【解决方案1】:

重要说明:(基于@Tashi 评论,我添加了此说明)如果您使用带有管理面板的 mvc 基本应用程序,则不必担心带有会话管理的整个应用程序的身份验证和授权.

当我们明确使用我们的应用程序定制时,我们需要它并且必须在每个控制器中实现。不要使用直接控制器进行继承,即MainController : Controller,而是使用自定义控制器来检查身份验证。

/*You have to inherit this basecontroller in every controller*/
public class MainController : BaseController
{
     your actionmethods
}

和 BaseController 一样

public class BaseController : Controller
    {

        public BaseController()
        {
            if (string.IsNullOrEmpty(SessionManager.SiteUrl))
            {
                SessionManager.SiteUrl = ConfigurationManager.AppSettings["SiteUrl"].ToString();
            }
        }

        protected override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            base.OnActionExecuting(filterContext);
            if (SessionManager.UserId == -1)
            {
                switch (filterContext.ActionDescriptor.ActionName.ToLower().Trim())
                {
                    case "addeditcontact":
                       ViewBag.hdnPopupLogout = "0";
                       return;
                    default:
                        filterContext.Result = new   RedirectResult(Url.Action("Login", "Home"));
                        break;
                }
            }
        }
}

为会话管理添加另一个属性类

public class SessionManager
{        

    public static int UserId
    {
        get
        {
            if (HttpContext.Current.Session["UserId"] != null)
            {
                return Convert.ToInt32(HttpContext.Current.Session["UserId"]);
            }
            else return -1;
        }
        set
        {
            HttpContext.Current.Session["UserId"] = value;
        }
    }

    public static string UserName
    {
        get
        {
            if (HttpContext.Current.Session["UserName"] != null)
            {
                return Convert.ToString(HttpContext.Current.Session["UserName"]);
            }
            else return string.Empty;
        }
        set
        {
            HttpContext.Current.Session["UserName"] = value;
        }
    }

   //reset user detail and add your custom property 
     public static void SignOutUser()
    {

        UserId = -1;
        UserName = string.Empty;          

    }

}

同时登录在 HomeController 中的会话变量中设置用户 ID,如

public ActionResult Login()
    {
        if (SessionManager.UserId == -1)
        {
            HttpCookie cookie = Request.Cookies["Login"];// Request.Cookies["Login"];

            if (cookie != null)
            {
                ViewBag.hdnUserID = cookie.Values[0];
                ViewBag.hdnPassword = cookie.Values[1];
                ViewBag.hdnRemember = "true";
            }
            return View("Login");
        }
        else
        {
            return RedirectToAction("Index", "Home");
        }
    }

现在你的架构准备好了,我会给你答案

  1. 如果没有用户,以上内容可以防止未经授权的访问 无需身份验证。
  2. 现在第二个问题是点击超链接时重定向到编辑页面。为此,在定义超链接时,可以创建动作方法来重定向,也可以使用 javascript / ajax 方法(用于身份验证)来重定向页面。

您需要在最后为网格设计 html。如下图。

及以上 html 中最后一个 td 的单元格呈现为 this

<td width="25%" >
   <a title="Edit" style="cursor:pointer" onclick="popupContacts(-2147481891,false );">Edit</a>&nbsp;
   <a style="cursor:pointer" title="Associate With Client" onclick="popupAssociateClient(-2147481891 );">Associate With Client</a>&nbsp;
   <a style="cursor:pointer" title="Update Contacts" onclick="popupUpdateContacts(-2147481891 );">Update Contacts</a>&nbsp;<a style="cursor:pointer" title="Export VCF" onclick="ExportContacttoVcf(-2147481891 );">Export VCF</a>&nbsp;
</td>

对于js,重定向到另一个页面,我们首先检查用户是否有适当的权限,否则重定向到actionmethod登录。

 function popupContactsDetails(clientid, contype) {          
        window.location.href = URL + "Home/ShowEditContact?Id=" + clientid + ",contype=" + contype;
    }

或者您可以使用相同的功能(可能是代码中的某些问题,因为我在此处发布代码,但要了解其背后的概念)

function popupContactsDetails(clientid, contype) {
 $.ajax({
        url: URL + "Home/ShowEditContact?Id=" + clientid + ",contype=" +      contype,
        type: 'get',
        dataType: 'json',
        async: false,
        //  data: ko.toJSON(this),
        contentType: 'application/json',
        success: function (result) {
            if (result = null) {
                alert("you are access wrong page);
                window.location.href = URL + "Home/login;
            } else{
                window.location.href = URL + "Home/yourpageurl; 
            }

        }
    });
}

【讨论】:

  • 嗨,你能解释一下你的第二个答案吗?为此,我一直认为从超链接中获取 id。即:字符串 id = ID-001。在登录控制器中,检查字符串 id 是否不为空。如果是,则重定向到编辑。如果不重定向到主。但我不知道如何从超链接中获取 ID。
  • 这个答案有很多错误的地方。除非您别无选择,否则应避免会话(您可以从HttpContext.Current 获取当前用户)。硬编码动作名称是错误的。您可以使用全局身份验证过滤器而不是基本控制器。 JS 中的硬编码 URL 破坏了 MVC 路由机制。我可以继续,但这里的评论长度有限制。
  • 是的,我知道这可能是错误的,但它仍然在我们的项目中工作,因为我们需要自定义身份验证,因此我们构建了它。如果您有更好的答案,请添加它。
猜你喜欢
  • 2019-09-17
  • 1970-01-01
  • 2015-05-04
  • 2017-12-25
  • 1970-01-01
  • 2021-01-05
  • 1970-01-01
  • 2015-03-12
  • 2012-06-28
相关资源
最近更新 更多