【问题标题】:MVC: Generate unique url for each userMVC:为每个用户生成唯一的 url
【发布时间】:2014-03-09 08:59:38
【问题描述】:

我想为每个用户创建唯一的 url,以便我可以将该 url 发送到他们的电子邮件,并按照该 url 发布他们的回复。

例如, 让我们假设有一个 Id 类型为 guid 的约会,并且有一些人(参加者)将参加某个约会。这些与会者还将拥有自己的 guid 类型 ID。

因此,要发布回复,用户将获得一个包含约会 ID 和他/她的参加者 ID 的 url,并且在单击该 url 时,如果我有一个如下所示的控制器,它会将用户转发到该控制器

   public class ResponseController : Controller
    {

        [HttpGet]
        public AttendeeResponse(Guid appointmentId, Guid attendeeId)
        {
           return View();
        }
   }

我应该如何生成这种url?

如果我只有一个参数(例如,appointmentid)

   public class AppointmentController : Controller
    {

        [HttpGet]
        public Create(Guid appointmentId)
        {
           return View();
        }
   }

这就是 url 的样子,将我转发到控制器中的上述方法

http://localhost:14834/Appointment/Create?appointmentId=e2fd8b29-2769-406a-b03d-203f9675edde

但是如果我必须用两个参数自己创建唯一的 url,我该怎么做呢?

【问题讨论】:

    标签: asp.net-mvc routing asp.net-mvc-routing asp.net-mvc-5


    【解决方案1】:

    要在 url 中添加更多参数,您可以使用 & 字符分隔 url 上的参数,例如:

    http://localhost:14834/Appointment/Create?appointmentId=e2fd8b29-2769-406a-b03d-203f9675edde&attendeeId=e2fd8b29-2769-406a-b03d-203f9675edde
    

    asp.net mvc 会为你绑定到你操作的Guid 对象上。

    代码示例:

    public static string CreateUrl(Guid appointmentId, Guid attendeeId)
    {
        return string.Format("http://yourdomain.com/Response/AttendeeResponse?appointmentId={0}&attendeeId={1}", appointmentId.ToString(), attendeeId.ToString());
    }
    

    既然你有 guids 对象,你可以使用这个方法,例如:

    string url = CreateUrl(appointmentGuid, attendeeguid);
    

    另一种解决方案

    不管怎样,你有什么地方可以存储约会的吗?我的意思是,数据库中的一个表用于示例。

    也许您可以执行以下步骤:

    1. 您可以为appointmentId 生成一个Guid,为attendeeId 生成另一个Guid。
    2. 将其存储在数据库中以供将来访问。
    3. 将带有appointmentId 的网址发送到用户的电子邮件。
    4. 当用户点击 URL 时,在您的操作中,您可以从数据库中读取 attendeeId 对应的 appointmentId 是什么。

    【讨论】:

    • 我有一个名为 Attendees 的表,其中包含 AppointmentIdAttendeeId 我需要根据表中的值生成 url
    • 因此,您可以从数据库中创建它并生成一个类似于上面示例的 url。以&分隔参数。
    • 你能举个例子吗?假设 var appointmentId = someguidIdvar attendeeId=someguidid 那么我如何创建 url?string url = "http://localhost:14834/Appointment/Create?appointmentId="+appointmentId+"&attendeeId="+attendeeId 类似的东西?
    • 感谢您在此之前试一试 +1 的帮助 ;)
    猜你喜欢
    • 2013-03-14
    • 1970-01-01
    • 1970-01-01
    • 2018-06-25
    • 2016-05-20
    • 2019-03-25
    • 1970-01-01
    • 1970-01-01
    • 2020-05-19
    相关资源
    最近更新 更多