简体   繁体   English

使用远程验证、MVC 和 Razor Pages .NET Core 2.2 失败 :::“InvalidOperationException: 找不到远程验证的 URL”

[英]Fail using Remote Validation, MVC, and Razor Pages .NET Core 2.2 ::: “InvalidOperationException: No URL for remote validation could be found”

Goal: Double-check Username for existence when making new account using Razor Pages .NET Core 2.2 and MVC.目标:使用 Razor Pages .NET Core 2.2 和 MVC 创建新帐户时,请仔细检查用户名是否存在。

Error: InvalidOperationException: No URL for remote validation could be found.错误:InvalidOperationException:找不到用于远程验证的 URL。

I have looked at other StackOverflow threads but I do not have any solution at this time.我查看了其他 StackOverflow 线程,但目前没有任何解决方案。

My Data Annotation for UserName input:我的用户名输入数据注释:

[Microsoft.AspNetCore.Mvc.Remote("IsUserNameUsed", "ValidationsController", ErrorMessage = "Username is taken.")]
public string UserName { get; set; }

My code inside Controller ValidationsController:我在 Controller ValidationsController 中的代码:

  public IActionResult IsUserNameUsed([Bind(Prefix = "Accounts.UserName")] string username)
        { 
            string query = "SELECT UserName FROM Accounts WHERE UserName={0}";
            var found = _context.Accounts
            .FromSql(query, username)
            .FirstOrDefault();

            if (found.Equals(username))
            {
                return Json(true);
            }
            else
            { 
            return Json(false);
            }
        }

I get this error when trying to navigate to the Razor Page in question.尝试导航到相关 Razor 页面时出现此错误。

InvalidOperationException: No URL for remote validation could be found.
 <input asp-for="Accounts.UserName" class="form-control" />

I found mention of adding MVC route to a strictly Razor Pages application.我发现提到将 MVC 路由添加到严格的 Razor Pages 应用程序。 I added the code below but I get the error no matter what I add.我添加了下面的代码,但无论我添加什么都会出现错误。

app.UseMvc(routes =>
{
    routes.MapRoute(
        name: "default",
        template: "{controller=Home}/{action=Index}/{id?}");
});

I tried different route values using actual Controller name and it's task:我使用实际的控制器名称尝试了不同的路由值,它的任务是:

routes.MapRoute(
    name: "default",
    template: "{controller=Validations}/{action=IsUserNameUsed}/{username?}");

another try (no "?"):另一个尝试(没有“?”):

  name: "default",
    template: "{controller=Validations}/{action=IsUserNameUsed}/{username}");

again another(no username):再次另一个(没有用户名):

name: "default",
template: "{controller=Validations}/{action=IsUserNameUsed}");

I know if it was a snake it would have bit me but I am totally dumbfounded.我知道如果它是一条蛇,它会咬我,但我完全傻眼了。

I still get "InvalidOperationException: No URL for remote validation could be found."我仍然收到“InvalidOperationException:找不到用于远程验证的 URL”。

This is the Data Annotation in my Accounts.cs Model for the UserName:这是我的 Accounts.cs 模型中用户名的数据注释:

   [Required]
    [Remote("IsUserNameUsed", "Validations",ErrorMessage ="UserName already exists" ,HttpMethod ="post")]
    public string UserName { get; set; }

This is the UserName input on the .cshtml Razor Page:这是 .cshtml Razor 页面上的用户名输入:

<div class="form-group">
    <label asp-for="Accounts.UserName" class="control-label"></label>
    <input asp-for="Accounts.UserName" class="form-control" />
    <span asp-validation-for="Accounts.UserName" class="text-danger"></span>
</div>

This is the Action (JsonResult) in the Controller (ValidationsController).这是控制器 (ValidationsController) 中的 Action (JsonResult)。 Notice inside the paranthesis the Binding of UserName field.注意括号内的 UserName 字段的绑定。 Without this syntax returns null.如果没有此语法,则返回 null。 And has to be set in the Controller/Json, not in the Model -- [Bind(Prefix = "Accounts.UserName")] string NameEntered :并且必须在控制器/Json 中设置,而不是在模型中设置 -- [Bind(Prefix = "Accounts.UserName")] 字符串 NameEntered

public JsonResult IsUserNameUsed([Bind(Prefix = "Accounts.UserName")] string NameEntered)
{
    bool UserNameExists = _context.Accounts.Any(u => u.UserName.Equals(NameEntered));

    return new JsonResult(!UserNameExists);  //NOTICE OPPOSITE BOOLEAN
}

Also notice above how I hit the database table for existence with one line and return the JsonResult with only one other line.还要注意上面我是如何用一行命中数据库表并仅用另一行返回 JsonResult 的。 It's kind of a negative binary on off that you have to test to get it right because true(found) really means false(can't use).这是一种负二进制,你必须测试才能正确,因为 true(found) 真的意味着 false(不能使用)。

Now, here is where I kept getting that error saying my route was wrong.现在,这是我不断收到错误消息的地方,说我的路线错误。

“InvalidOperationException: No URL for remote validation could be found” “InvalidOperationException:找不到远程验证的 URL”

So I tried referencing in the Model a custom named JsonResult("IsUserNameUsed") and in a custom name Controller("Validations") and giving that path in the Model:所以我尝试在模型中引用一个名为 JsonResult("IsUserNameUsed") 的自定义名称和一个自定义名称 Controller("Validations") 并在模型中给出该路径:

[Remote("IsUserNameUsed", "Validations",ErrorMessage ="UserName already exists" ,HttpMethod ="post")]

I didn't know it but I was onto something.我不知道,但我正在做某事。 . . . . but .但 。 . . . . . . . . Since it is a Razor Pages .NET Core 2.2 app I still had to create a "using Microsoft.AspNetCore.Mvc" at the top of the Controller and put this in the Startup.cs file in Configure section.由于它是 Razor Pages .NET Core 2.2 应用程序,我仍然必须在控制器顶部创建一个“使用 Microsoft.AspNetCore.Mvc”并将其放入配置部分的 Startup.cs 文件中。

app.UseMvc(routes =>
{
    routes.MapRoute(
        name: "default",
        template: "{controller=Home}/{action=Index}/{id?}");
});

Notice the above route is the default route that comes with an MVC application (website opens to the Index page).请注意,上面的路由是 MVC 应用程序附带的默认路由(网站打开到索引页面)。 Funny how it is using "id?"有趣的是它是如何使用“id”的? even though I am validating a string.I excluded a HomeController I had added thinking it would trigger an error if it didn't exist.即使我正在验证一个字符串。我排除了我添加的 HomeController,认为如果它不存在会触发错误。 But.但。 . . .no error. .没有错误。 . . .just the default MVC route template is needed in Startup.cs and one custom named controller and 2 different routes. .只需要 Startup.cs 中的默认 MVC 路由模板和一个自定义命名的控制器和 2 个不同的路由。

However, the 2 routes is what makes my custom Controller JsonResult URL work coming from the Model's Data Annotation.但是,这 2 条路线使我的自定义控制器 JsonResult URL 工作来自模型的数据注释。 Clear as mud?清如泥? A default route needed to use MVC custom route, go figure.使用 MVC 自定义路由所需的默认路由,请看图。

and now you know the rest of the story.现在你知道故事的其余部分了。

Caveat: I am using 2.2 but if you have 3.0 there is now a "RemotePage" data annotation and MVC is not needed.警告:我使用的是 2.2,但如果你有 3.0,现在有一个“RemotePage”数据注释,不需要 MVC。 You can find this on https://www.learnrazorpages.com/您可以在https://www.learnrazorpages.com/上找到它

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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