Open Specified ASP.NET MVC Views From Hyperlinks Inside Email Body

会有一股神秘感。 提交于 2021-02-10 22:20:31

问题


I just learn about ASP.NET MVC. I hava a website with this following scenario:

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

So, In LoginController when user login, it will redirect to main page and edit a record from MainPage.

Everytime a new record is created through ASP.NET MVC, the system will send an email to manager. Within email message, there is a hyperlink that will redirect the manager to edit form. But first, he needs to login because the edit form cant be opened unless he login. Ex:

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

I have add Authorize Attribute within MainController. But It's only work for Main Page. So I can open Edit Page even I am not login yet.

Here is the MainController:

[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();
    }
}

The Second Question, Above I have write my website scenario, that is

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

Based On Hyperlink On Email, How to make application Redirect to EditPage without redirect to MainPage.

Login -> EditPage (Edit)

EDITED 2nd question

In short, when user's trying to access edit view directly, the application will redirect user to login view. And when heelr login success , the application will redirect user to Edit View.

But now, when login success, the system will redirect the user to main view. How to make the application redirect to edit view after login ?


回答1:


Important note : (Based on @Tashi Comment, I added this note) If you are use mvc basic application with admin panel than do not worry about the authentication and authorization for whole application with session management.

This is we need when we explicitly use our customization of app and that has to be implement in every controller. Rather than use direct controller for inheritance i.e. MainController : Controller , use custom controller where you check authentication.

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

And BaseController like

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;
                }
            }
        }
}

Add another property class for session management

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;          

    }

}

While login set userid in session variable in HomeController like

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");
        }
    }

Now this is your architecture ready, I will give your answer

  1. This above things prevent unauthorized access, if there is no user without authentication.
  2. Now second question is redirect to edit page when hyperlink click. for this while define hyperlink, either create actionmethod to redirect or you can use javascript / ajax method (For authenication) to redirect page.

You need to design html at your end for grid. As this below image.

and above last td of cell in html render as 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>

for js, redirect to another page, where we first check that user have proper rights else redirect to login in actionmethod.

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

OR You can use the same function as(may be some thing wrong in code as I maniputlate code to publish here, but understand the concept behind this)

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; 
            }

        }
    });
}


来源:https://stackoverflow.com/questions/45929947/open-specified-asp-net-mvc-views-from-hyperlinks-inside-email-body

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!