如何调用一些Controller的方法并从查询字符串传递参数

时间:2018-05-03 21:26:16

标签: asp.net-mvc-4 query-string actionmethod

在我的应用中,我生成了一个这样的网址:

http://www.test.com/?mail=test%40gmail.ba&code=71147ff9-87ae-41fc-b53f-5ecb3dbe5a01

我生成Url的方式发布在下面:

private string GenerateUrl(string longUrl, string email, string confirmCode)
{
    try
    {
        // By the way this is not working (Home/MailConfirmed) I'm getting message 
        // Requested URL: /Home/MailConfirmed
        // The resource cannot be found.
        string url = longUrl + "/Home/MailConfirmed";
        var uriBuilder = new UriBuilder(url);
        var query = HttpUtility.ParseQueryString(uriBuilder.Query);
        query["mail"] = email;
        query["code"] = confirmCode;
        uriBuilder.Query = query.ToString();
        uriBuilder.Port = -1;
        url = uriBuilder.ToString();
        return url;
    }
    catch (Exception ex)
    {
        return "Error happened: " + ex.Message;
    }
}
  

在longUrl我通过www.test.com,在电子邮件中我正在通过   test@gmail.com等等..

有关于我网站的信息:

www.test.com

邮件:test@gmail.com

confirmcode:71147ff9-87ae-41fc-b53f-5ecb3dbe5a01

在我的HomeController.cs中有一个方法应该从查询字符串中取出参数 - url并将其传递给应该通过邮件获取用户来激活用户帐户的方法(邮件是唯一的)并比较这个guid用数据库中的guid。所以我想知道如何调用这种方法?

所以我的方法看起来像这样:

 public  JsonResult MailConfirmed(string mail, string confirmCode)
 {
       try
       {
           // Here I will get user and update it in DB
              return Json("success", JsonRequestBehavior.AllowGet);
       }
       catch(Exception ex)
       {
           return Json("fail", JsonRequestBehavior.AllowGet);
       }
  }

所以我的问题是如何让用户点击以下链接并调用我的方法..?

非常感谢 干杯

1 个答案:

答案 0 :(得分:1)

要导航到您的MailConfirmed(),您的网址必须

http://www.test.com/Home/MailConfirmed?mail=test%40gmail.ba&confirmcode=71147ff9-87ae-41fc-b53f-5ecb3dbe5a01

请注意控制器和操作名称的段,code=xxx应为confirmcode=xxx以匹配方法中参数的名称。

您可以使用GenerateUrl()方法生成网址来简化代码(并删除UrlHelper方法)。

要生成上述网址,您在控制器方法中所需要的只是

string url = Url.Action("MailConfirmed", "Home", 
    new { mail = email, confirmcode = confirmCode },
    this.Request.Url.Scheme);
相关问题