ASP.NET Core创建回调URL出错:确认邮件回调URL生成返回Null问题求助
Let's walk through the typical issues that might be causing your Url.Action call to return null when generating the confirm email callback URL, along with fixes for each:
Mismatched action/controller naming
ASP.NET expects action method names to use PascalCase (likeConfirmEmail), not kebab-case (confirm-email). If your controller method is namedConfirmEmail, you need to pass that exact string toUrl.Action—the framework won't automatically convert kebab-case to PascalCase here. Double-check that your action name in the code matches the actual method name in yourAccountController.Incorrect controller class name
Make sure your controller class is namedAccountController(theControllersuffix is mandatory). If it's named something likeAccountorAccountsController,Url.Actionwon't be able to locate it, resulting in a null return value.Invalid or missing Request.Scheme
If you're running this code outside of an HTTP request context (like a background service, console app, or a place whereRequestisn't available),Request.Schemewill be null or empty.Url.Actionneeds a valid scheme (http/https) to build a full absolute URL. You can fix this by hardcoding the scheme temporarily for testing, or ensuring you're in a valid request context:var callbackUrl = Url.Action("ConfirmEmail", "Account", new { token, email }, "https");Uninitialized UrlHelper
If this code isn't running inside a controller, view, or a service whereUrlHelperis properly injected, theUrlobject might not be set up correctly. For custom services, you'll need to injectIUrlHelperFactoryandActionContextto create a validUrlHelperinstance:// In your service constructor private readonly IUrlHelperFactory _urlHelperFactory; private readonly ActionContext _actionContext; public YourService(IUrlHelperFactory urlHelperFactory, ActionContext actionContext) { _urlHelperFactory = urlHelperFactory; _actionContext = actionContext; } // When generating the URL var urlHelper = _urlHelperFactory.GetUrlHelper(_actionContext); var callbackUrl = urlHelper.Action("ConfirmEmail", "Account", new { token, email }, "https");Broken routing configuration
Check your route setup (inStartup.csfor .NET Core orRouteConfig.csfor .NET Framework) to ensure it includes placeholders for controller and action. The default route should look something like this:app.UseEndpoints(endpoints => { endpoints.MapControllerRoute( name: "default", pattern: "{controller=Home}/{action=Index}/{id?}"); });If your routes don't include
{controller}and{action},Url.Actioncan't map your controller/action pair to a valid URL path.
内容的提问来源于stack exchange,提问作者Muhammad farhan




