获取操作的绝对URL(不在视图中) - NullReferenceException

时间:2015-09-01 19:14:15

标签: c# .net asp.net-mvc url-routing

我已经搜索了很多这个问题并且它们似乎都有相同的答案,似乎属于由视图而不是控制器调用。

我已尝试实施答案,但我在这部分NullReferenceException上获得了url.RequestContext.HttpContext.Request.Url.Scheme;

我引用了System.Web.Mvc;,但我仍无法拨打Url.Action。相反,我必须创建UrlHelper的新对象,然后调用Action方法。我不确定这是否是我的问题的原因。

我的代码如下:

    public static class EmailHelper
            {

             public static string AbsoluteAction(this UrlHelper url, string actionName, string controllerName, object routeValues = null)
                {
                    // Throws NullReferenceException
                    string scheme = url.RequestContext.HttpContext.Request.Url.Scheme;

                    return url.Action(actionName, controllerName, routeValues, scheme);
                }

             public static async Task SendReset(string emailAddress)
                {
                    MailDefinition md = new MailDefinition()
                    {
                        IsBodyHtml = true,
                        Subject = "Password Reset",
                        BodyFileName = "~/Templates/ResetConfirm.html",
                    };


                    UrlHelper helper = new UrlHelper();
                    string url = helper.AbsoluteAction("Login", "Account");

                    ListDictionary replacements = new ListDictionary();
                    replacements.Add("{{LoginUrl}}", url);

                    MailMessage msg = md.CreateMailMessage(emailAddress, replacements, new System.Web.UI.Control());
                    SmtpClient client = new SmtpClient();

                    await client.SendMailAsync(msg);
                }
            }

修改

我从SendReset的{​​{1}}帖子操作中致电AccountController

ResetPassword

1 个答案:

答案 0 :(得分:2)

UrlHelper属性Url也可以在控制器中访问,因此请将该实例提供给您的方法以访问UrlHelper

public async Task<ActionResult> ResetPassword(ResetPasswordViewModel model)
{
    // some code here...
    await EmailHelper.SendReset(Url, model.Email);
    //...
}


public static class EmailHelper
{
    public static async Task SendReset(UrlHelper urlHelper, string emailAddress)
    {
        //...
        string url = urlHelper.AbsoluteAction("Login", "Account");
    }
}