简体   繁体   中英

How can get nullable string value?

[HttpGet]
public ActionResult Login(string? returnUrl)
{
    if (Request.IsAuthenticated)
    {
        if(returnUrl.HasValue)
           return RedirectToAction("Index", "Home");
        else
           return RedirectToAction(returnUrl);
    }
    return View();
}

在此处输入图片说明

Error: The best overloaded method match for 'System.Web.Mbv.Controller.Redirect(string)' has some invalid arguments

How can use nullable string for RedirectToAction()

String is nullable already but you can check for null with string.IsNullOrEmpty.

[HttpGet]
public ActionResult Login(string returnUrl)
{
        if (Request.IsAuthenticated)
        {
           if(string.IsNullOrEmpty(returnUrl))
           {
               return RedirectToAction("Index", "Home");
           }
           else
           {
               return RedirectToAction(returnUrl);
           }
        }
        return View();
}

You could also default it so if it's not passed in it will never be empty.

[HttpGet]
    public ActionResult Login(string returnUrl = "www.yourDomain.com/login")
    {
            if (Request.IsAuthenticated)
            {
               return RedirectToAction(returnUrl);
            }
            return View();
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM