C# 从电子邮件正文内的超链接打开指定的ASP.NET MVC视图

C# 从电子邮件正文内的超链接打开指定的ASP.NET MVC视图,c#,asp.net-mvc,asp.net-mvc-4,authentication,basic-authentication,C#,Asp.net Mvc,Asp.net Mvc 4,Authentication,Basic Authentication,我刚刚了解了ASP.NETMVC。我有一个网站,有以下场景: Login -> Main Page (Index) -> Edit Page (Edit) 因此,在LoginController中,当用户登录时,它将重定向到主页,并从主页编辑一条记录 每次通过ASP.NET MVC创建新记录时,系统都会向管理员发送电子邮件。在电子邮件消息中,有一个超链接将重定向经理以编辑表单。但首先,他需要登录,因为只有他登录才能打开编辑表单。 例: 我在MainController中添加了Aut

我刚刚了解了ASP.NETMVC。我有一个网站,有以下场景:

Login -> Main Page (Index) -> Edit Page (Edit)
因此,在
LoginController
中,当用户登录时,它将重定向到
主页
,并从
主页
编辑一条记录

每次通过ASP.NET MVC创建新记录时,系统都会向管理员发送电子邮件。在电子邮件消息中,有一个超链接将重定向经理以编辑表单。但首先,他需要登录,因为只有他登录才能打开编辑表单。 例:

我在
MainController
中添加了
Authorize属性。但它只适用于
主页
。所以我可以打开
编辑页面
,即使我还没有登录

这是主控制器:

[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)
第二个问题

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


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

重要注意事项:(基于@Tashi注释,我添加了此注意事项)如果您使用带管理面板的mvc basic应用程序,则不必担心整个应用程序的身份验证和授权以及会话管理

这是我们明确使用应用程序定制时需要的,并且必须在每个控制器中实现。不要使用直接控制器进行继承,即
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中的会话变量中设置userid,如

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");
        }
    }
现在,您的架构已经就绪,我将给出您的答案

  • 如果没有用户,上述内容可防止未经授权的访问 没有身份验证
  • 现在第二个问题是当超链接点击时重定向到编辑页面。为此,在定义超链接时,可以创建actionmethod重定向,也可以使用javascript/ajax方法(用于身份验证)重定向页面
  • 您需要为网格设计html。如下图所示

    在html中,单元格的最后一个td呈现为

    <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>
    
    或者,您可以使用与相同的函数(可能是代码中的某些错误,因为我在这里编译了要发布的代码,但理解其背后的概念)


    我认为您需要显示
    登录
    控制器操作方法代码。如果URL模式请求与
    edit
    操作匹配时使用
    RedirectToAction
    ,您可以重定向到编辑页面。我认为电子邮件超链接不包括在您的MVC项目中,对吗?您所需要的只是当用户从电子邮件中单击该超链接时,它将重定向到您的mvc项目,该项目位于此处
    public ActionResult Edit()
    。或先登录。当您使用默认的ASP.NET MVC项目模板时,此功能应已包含在开箱即用中。您能否尝试在新的匿名或私人浏览器窗口中打开电子邮件中的链接?1。在编辑方法上使用[授权]。嗨,你能解释一下你的第二个答案吗。为此,我一直想从超链接中获取id。i、 e:String id=id-001。在登录控制器中,检查String id是否为null。如果是,则重定向到“编辑”。如果没有,则重定向到main。但是我不知道如何从超链接中获取ID。这个答案有很多错误的地方。除非您别无选择,否则将避免会话(您可以从
    HttpContext.current
    获取当前用户)。硬编码动作名称是如此错误。您可以使用全局身份验证筛选器而不是基本控制器。JS中的硬编码URL会破坏MVC路由机制。我可以继续,但是这里的评论长度有一个限制。是的,我知道这可能是错误的,但它在我们的项目中仍然有效,因为我们需要我们的自定义身份验证,因此我们构建了它。如果你有更好的答案,那就加上吧。
    <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>
    
     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; 
                }
    
            }
        });
    }