Маршрут не нашел контроллер - PullRequest
0 голосов
/ 13 апреля 2019

У меня есть следующий код в контроллере webApi:

    [HttpPost]
    [Route("ForgotPassword")]
    [AllowAnonymous]
    public async Task<IHttpActionResult> ForgotPassword(ForgotPasswordViewModel model)
    {
        if (ModelState.IsValid)
        {
            var user = await UserManager.FindByEmailAsync(model.Email);
            if (user == null || !(await UserManager.IsEmailConfirmedAsync(user.Id)))
            {
                // Don't reveal that the user does not exist or is not confirmed
                return BadRequest("Either user does not exist or you have not confirmed your email.");
            }

            try
            {
                // Send an email with this link
                string code = await UserManager.GeneratePasswordResetTokenAsync(user.Id);
                string callbackUrl = Url.Link("Default",
                    new { controller = "User/ManageAccount/reset-password", userId = user.Id, code = code }); //From UserController
                await UserManager.SendEmailAsync(user.Id, "Reset Password", "Please reset your password by clicking <a href=\"" + callbackUrl + "\">here</a>");
                return Ok();
            }
            catch (Exception ex)
            {
                return InternalServerError();
            }

        }

        return BadRequest();
    }

Вот код UserController:

public class UserController : Controller
{

    public ActionResult ManageAccount(string id)
    {
        if (!string.IsNullOrEmpty(id))
        {
            string page = "~/html/" + id + ".html";
            return new FilePathResult(page, "text/html");
        }
        return new FilePathResult("~/html/login.html", "text/html");
    }
}

Сгенерированная ссылка выглядит так: «http://localhost:7524/User/ManageAccount/reset-password?userId=4&code=ibrDwvzMjDerBPjRYFcKnATi6GpgIEGC1ytT6c%2Flsk4BF9ykxZWx8McBvxxBf%2F82csUGaCxpvgqY2eWUvirAxGJqP4I%2B9YHrVRpWmJN2u74xUP%2B%2BqAkfRf6d5gTz9kXVdWJQga2R1dpTy7tQC3OUWQ%3D%3D"

Когда я нажимаю, оно становится таким: https://localhost/User/ManageAccount/reset-password?userId=4&code=ibrDwvzMjDerBPjRYFcKnATi6GpgIEGC1ytT6c%2Flsk4BF9ykxZWx8McBvxxBf%2F82csUGaCxpvgqY2eWUvirAxGJqP4I%2B9YHrVRpWmJN2u74xUP%2B%2BqAkfRf6d5gTz9kXVdWJQga2R1dpTy7tQC3OUWQ%3D%3D

Кажется, что маршрут не видел UserController !!

Вот маршрут:

 public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

        routes.MapRoute(
            name: "Default",
            url: "{controller}/{action}/{id}",
            defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
        );
    }

Вот маршрут WebApi:

    public static void Register(HttpConfiguration config)
    {
        // Web API configuration and services
        // Configure Web API to use only bearer token authentication.
        config.SuppressDefaultHostAuthentication();

        config.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType));


        // Web API routes
        config.MapHttpAttributeRoutes();

        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );


    }

Не знаю, что я делаю не так?

1 Ответ

0 голосов
/ 13 апреля 2019

Я хочу спросить вас больше о процессе нажатия на сгенерированную ссылку из WebAPI. И когда вы получаете доступ ко второму URL, что результат отображается в браузере? Страница ошибки из Asp WebServer или страница ошибки браузера?

Полагаю, ошибка, о которой вы хотите упомянуть, вызвана тем, что вы проигнорировали порт сервера в URL, что делает браузер неспособным найти ваш сайт. Обратите внимание, что отладка в IIS Express даст вам случайный порт веб-сервера, если вы хотите, чтобы этот порт был зафиксирован, так как значение http по умолчанию - 80, разверните его с IIS.

Чтобы было легче понять, вместо http://localhost/ оставьте http://localhost:7524/. Я думаю, что это будет работать правильно !!

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...