【问题标题】:Clicking a Button in a Form produces "The resource cannot be found"单击表单中的按钮会产生“找不到资源”
【发布时间】:2015-09-08 15:15:42
【问题描述】:

我有一个显示事件详细信息的详细信息页面。

此页面底部有一个注册按钮。

@using (Html.BeginForm("Register", "Events", new { eventId = Model.Id }, FormMethod.Post, null))
{
    @Html.AntiForgeryToken()
<div id="">
    <p>
        @*<button type="submit" class="btn btn-default" id="btnEnrol" name="btnEnrol" value="@Model.Id" title="Register">Register</button>*@
        <input type="submit" class="btn btn-default" id="btnEnrol" name="btnEnrol" value="Register" />
    </p>
</div>
}

这是我的控制器方法:

[HttpPost]
[Authorize]
[ValidateAntiForgeryToken]
public ActionResult Register(int eventId)
{
    if (eventId == 0)
        return View("Index");

    var now = DateTime.Now;

    var userId = User.Identity.GetUserId();

    var registration = this.repo.GetRegistration(eventId, userId);

    if (registration != null)
    {
        ViewBag.Registered = true;
    }
    else
    {
        var successful = this.repo.RegisterEvent(eventId, userId);

        if (successful)
        {
            return View();
        }
        else
        {
            return View();
        }
    }
    return View();
}

这是点击注册按钮后的链接

http://localhost/lrc/Events/Register?eventId=7

这里是 RouteConfig.cs

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

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

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

我已经阅读了很多关于 SO 的帖子,但没有一个能解决我的问题。

我也尝试过:

删除了 [HttpPost] 注释,我认为它没有帮助,但这只是一个绝望的尝试。


更新 1

我在默认路由之前的 RouteConfig.cs 中添加了 1 个路由:

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

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

    routes.MapRoute(
        name: "myRoute",
        url: "Events/Register/{eventId}",
        defaults: new { controller = "Events", action = "Register", eventId = UrlParameter.Optional }
    );

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

然后我终于得到了一些不同的东西,但它仍然是一个错误:

“/lrc”应用程序中的服务器错误。

当前类型, Microsoft.AspNet.Identity.IUserStore`1[lrc.Models.ApplicationUser],是 一个接口,不能被构造。你错过了一个类型 映射?

描述:执行过程中发生了未处理的异常 当前的网络请求。请查看堆栈跟踪以获取更多信息 有关错误的信息以及它在代码中的来源。

异常详情:System.InvalidOperationException:当前类型, Microsoft.AspNet.Identity.IUserStore`1[lrc.Models.ApplicationUser],是 一个接口,不能被构造。你错过了一个类型 映射?

来源错误:

在执行过程中产生了一个未处理的异常 当前的网络请求。有关原产地和位置的信息 可以使用下面的异常堆栈跟踪来识别异常。

堆栈跟踪:

[InvalidOperationException:当前类型, Microsoft.AspNet.Identity.IUserStore1[lrc.Models.ApplicationUser], is an interface and cannot be constructed. Are you missing a type mapping?]
Microsoft.Practices.ObjectBuilder2.DynamicMethodConstructorStrategy.ThrowForAttemptingToConstructInterface(IBuilderContext context) +192 lambda_method(Closure , IBuilderContext ) +40
Microsoft.Practices.ObjectBuilder2.<>c__DisplayClass1.<GetBuildMethod>b__0(IBuilderContext context) +48
Microsoft.Practices.ObjectBuilder2.BuildPlanStrategy.PreBuildUp(IBuilderContext context) +323
Microsoft.Practices.ObjectBuilder2.StrategyChain.ExecuteBuildUp(IBuilderContext context) +349
Microsoft.Practices.ObjectBuilder2.BuilderContext.NewBuildUp(NamedTypeBuildKey newBuildKey) +254 lambda_method(Closure , IBuilderContext ) +200
Microsoft.Practices.ObjectBuilder2.<>c__DisplayClass1.<GetBuildMethod>b__0(IBuilderContext context) +48
Microsoft.Practices.ObjectBuilder2.BuildPlanStrategy.PreBuildUp(IBuilderContext context) +323
Microsoft.Practices.ObjectBuilder2.StrategyChain.ExecuteBuildUp(IBuilderContext context) +349
Microsoft.Practices.ObjectBuilder2.BuilderContext.NewBuildUp(NamedTypeBuildKey newBuildKey) +254 lambda_method(Closure , IBuilderContext ) +202
Microsoft.Practices.ObjectBuilder2.<>c__DisplayClass1.<GetBuildMethod>b__0(IBuilderContext context) +48
Microsoft.Practices.ObjectBuilder2.BuildPlanStrategy.PreBuildUp(IBuilderContext context) +323
Microsoft.Practices.ObjectBuilder2.StrategyChain.ExecuteBuildUp(IBuilderContext context) +349
Microsoft.Practices.Unity.UnityContainer.DoBuildUp(Type t, Object existing, String name, IEnumerable
1 resolverOverrides) +442

[ResolutionFailedException: 依赖解析失败,输入 =“lrc.Controllers.AccountController”,名称=“(无)”。异常发生时:解决时。例外是: InvalidOperationException - 当前类型, Microsoft.AspNet.Identity.IUserStore`1[lrc.Models.ApplicationUser],是 一个接口,不能被构造。你错过了一个类型 映射? - - - - - - - - - - - - - - - - - - - - - - - - 当时例外情况中,容器是:

正在解决 lrc.Controllers.AccountController,(none) 正在解决 构造函数的参数“userManager” lrc.Controllers.AccountController(lrc.ApplicationUserManager 用户管理器,lrc.ApplicationSignInManager 登录管理器) 解决 lrc.ApplicationUserManager,(无) 解析构造函数 lrc.ApplicationUserManager(Microsoft.AspNet.Identity.IUserStore1[[lrc.Models.ApplicationUser, lrc, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]] store) Resolving Microsoft.AspNet.Identity.IUserStore1[lrc.Models.ApplicationUser],(none) 的参数“store” ] Microsoft.Practices.Unity.UnityContainer.DoBuildUp(类型 t,对象 现有,字符串名称,IEnumerable1 resolverOverrides) +550
Microsoft.Practices.Unity.UnityContainer.DoBuildUp(Type t, String name, IEnumerable
1 resolverOverrides) +20
System.Web.Mvc.DefaultControllerActivator.Create(RequestContext requestContext, Type controllerType) +78

[InvalidOperationException: 尝试创建一个错误 'lrc.Controllers.AccountController' 类型的控制器。确保 控制器有一个无参数的公共构造函数。]
System.Web.Mvc.DefaultControllerActivator.Create(RequestContext requestContext,类型控制器类型)+256
System.Web.Mvc.DefaultControllerFactory.CreateController(RequestContext requestContext,字符串控制器名称)+169
System.Web.Mvc.MvcHandler.ProcessRequestInit(HttpContextBase httpContext、IController&控制器、IControllerFactory&工厂) +270 System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContextBase httpContext,AsyncCallback 回调,对象状态)+147
System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +12289179 System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +288

版本信息:Microsoft .NET Framework 版本:4.0.30319; ASP.NET 版本:4.0.30319.34248


更新 2

这是我的 EventsController 构造函数

    private ILRCRepository repo;

    public EventsController(ILRCRepository repository)
    {
        this.repo = repository;
    }

我在整个项目中搜索了 UserStore,只在一个地方(在 IdentityConfig.cs 中)找到了它:

// Configure the application user manager used in this application. UserManager is defined in ASP.NET Identity and is used by the application.
public class ApplicationUserManager : UserManager<ApplicationUser>
{
    public ApplicationUserManager(IUserStore<ApplicationUser> store)
        : base(store)
    {
    }

【问题讨论】:

  • 什么是Irc?你在使用区域吗?
  • 嗨 @StephenMuecke 这只是我网站的名称
  • 代码看起来没有任何问题。您有[Authorize] 属性,但该方法名为Register,表明用户尚未登录(因此不会被授权)。你试过[AllowAnonymous]吗?
  • hi@StephenMuecke 我同意代码应该没问题。我需要 [Authorize],因为只有注册用户才能注册活动。
  • 您是否尝试过创建特定路线(在默认之前) - 使用url: "Event/Register/{eventId}",

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


【解决方案1】:

发布会正常工作。正如@Stephen 在 cmets 中指出的那样,带有操作参数的帖子应该可以正常工作。

作为替代方案,如果由于某种原因它不起作用,您可以使用隐藏字段作为事件 ID:

Html.Hidden("eventId", Model.Id)

这将发布到动作就好了。

【讨论】:

  • OP 正在将该值添加为路由参数,它将回发并绑定。不需要隐藏输入
  • 我以为我以前尝试过一次,不得不使用隐藏的输入字段;我可能是错的。感谢您的更新。
  • 嗨,Brian,那我如何获得 id?
  • 您可以像上面一样在您的操作方法参数列表中定义 eventId,它将与您设置的方式一起使用。那么您是在尝试隐藏变量方法,还是查询字符串有效?
【解决方案2】:

我怀疑找不到资源与您的 RouteConfig.cs 期望 {id} 和您的 EventsController 期望 {eventId} 有关。

将您的 EventsController 方法更改为将 int id 作为输入参数:

[HttpPost]
[Authorize]
[ValidateAntiForgeryToken]
public ActionResult Register(int id)
{
    if (id == 0)
        return View("Index");

    var now = DateTime.Now;

    var userId = User.Identity.GetUserId();

    var registration = this.repo.GetRegistration(id, userId);

    if (registration != null)
    {
        ViewBag.Registered = true;
    }
    else
    {
        var successful = this.repo.RegisterEvent(id, userId);

        if (successful)
        {
            return View();
        }
        else
        {
            return View();
        }
    }
    return View();
}

或者,您可以更新 RouteConfig.cs 以包含带有 {eventId} 的路由:

        routes.MapRoute(
            name: "Event",
            url: "{Irc}/Events/Register/{eventId}",
            defaults: new { controller = "Events", action = "Register", eventId = UrlParameter.Optional }
        );

【讨论】:

  • 您好 ethom10,感谢您的帮助。我已经检查了 eventId 到 id 并在 RouteConfig.cs 中添加了路由,但问题仍然存在。
  • @Franva 是的,看起来您的问题很快就离开了路由区域并进入了依赖注入。
  • 我同意,它现在显示与 Unity DI 相关的另一个错误。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-09-08
  • 1970-01-01
相关资源
最近更新 更多