简体   繁体   English

MVC controller 被调用两次

[英]MVC controller is being called twice

I have a controller that is being called twice from an ActionLink call.我有一个 controller 从 ActionLink 调用中被调用两次。

My home page has a link, that when clicked calls the Index method on the Play controller.我的主页有一个链接,单击该链接时会调用 Play controller 上的 Index 方法。 An id of 100 is passed into the method.将 100 的 id 传递给该方法。 I think this is what is causing the issue.我认为这是导致问题的原因。 More on this below.更多关于这下面。

Here are some code snippets:以下是一些代码片段:

Home page:主页:

<%= Html.ActionLink("Click Me", "Index", "Play", new { id = 100 }, null) %>

Play Controller:播放 Controller:

public ActionResult Index(int? id)
{
    var settings = new Dictionary<string, string>();
    settings.Add("Id", id.ToString());
    ViewData["InitParams"] = settings.ToInitParams();
    return View();
}

Play view:播放视图:

<%@ Page Title="" Language="C#" Inherits="System.Web.Mvc.ViewPage" %>

(html <head> omitted for brevity)

<body>
    <form id="form1" runat="server" style="height:100%">
        Hello
    </form>
</body>

If I get rid of the parameter to the Index method, everything is fine.如果我摆脱 Index 方法的参数,一切都很好。 If I leave the parameter in place, then the Index method is called with 100 as the id.如果我将参数保留在原位,则使用 100 作为 id 调用 Index 方法。 After returning the View, the method is called a second time with a parameter of null.返回View后,第二次调用该方法,参数为null。

I can't seem to figure out what is triggering the second call.我似乎无法弄清楚是什么触发了第二次通话。

My first thought was to add a specific route like this:我的第一个想法是添加这样的特定路线:

routes.MapRoute(
    "Play", // Route name
    "Play/{id}", // URL with parameters
    new {controller = "Play", action = "Index"} // Parameter defaults
);

This had no effect other than making a prettier looking link.除了使链接看起来更漂亮之外,这没有任何作用。

I am not sure where to go from here.我不确定 go 从这里到哪里。

Is there any other markup that could be accidentally referencing the page?是否有任何其他标记可能会意外引用该页面? Script references, image references, css references, all could be mistakenly pointed at '.'脚本引用、图像引用、css 引用,都可能被错误地指向“.”。 or the current page.或当前页面。

10 hours chasing that bug in a Java Spring Maven project.在 Java Spring Maven 项目中追逐该错误 10 个小时。

First on SELECT I thought Hibernate was just logging twice, but then with INSERT I thought requests were called twice.首先在 SELECT 上,我认为 Hibernate 只是记录了两次,但是对于 INSERT,我认为请求被调用了两次。 Stepping throught the code I discovered controller was called twice...单步执行我发现控制器被调用两次的代码......

Tried all possible Spring configuration, thinking the context was loaded twice or a bean was instantiate twice...尝试了所有可能的 Spring 配置,认为上下文被加载了两次或者一个 bean 被实例化了两次......

In despair, rebuilded the project piece by piece to finally add a fragment of HTML and kaboom bug's back.无奈之下,把项目一点一点的重建,最后加了一段HTML和kaboom bug的背影。

<img alt="" src="#" />

The sharp sign was guilty, reloading the URL.尖锐的标志是有罪的,重新加载了 URL。 I know the topic is old, but I summarized my searchs with the words I used to look for in vain on Internet to find an answer to the same issue!我知道这个话题很老,但我用我以前在互联网上徒劳地寻找的词来总结我的搜索,以找到同一问题的答案! Could help others...可以帮助别人...

You can step through the code in your view.您可以单步执行视图中的代码。 Step through and see where the second call comes from.逐步查看第二个呼叫的来源。

While debugging I found out that a Partial View causes the the Controller to be called a second time.在调试时,我发现部分视图会导致控制器第二次被调用。 It sucks, but I don't see a work around that one.这很糟糕,但我没有看到解决这个问题的方法。

there should be a html markeup that is not working properly.应该有一个无法正常工作的 html 标记。 please check all img tage.请检查所有 img 标签。 also check还检查

<link rel="icon" href="favicon.ico" type="image/x-icon" />

Try changing the int? id尝试改变int? id int? id to int id . int? idint id It's matching the route the 2nd time because you're calling the index again with a null id.它第二次匹配路由,因为您再次使用空 ID 调用索引。

You can also try changing your route to this.您也可以尝试将您的路线更改为此。

routes.MapRoute( 
    "Play", // Route name 
    "Play/{id}", // URL with parameters 
    new { controller = "Play", action = "Index" , id = "" } // Parameter defaults 
);

I had this same issue and verified all the possible suggestions but no luck then I noticed following JS warning message in my Console.我遇到了同样的问题并验证了所有可能的建议,但没有运气,然后我注意到控制台中出现了以下 JS 警告消息。

Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user's experience.主线程上的同步 XMLHttpRequest 已被弃用,因为它会对最终用户的体验产生不利影响。 For more help, check https://xhr.spec.whatwg.org/ .如需更多帮助,请查看https://xhr.spec.whatwg.org/

 xmlHttp = new XMLHttpRequest();

I corrected this and it works for me.我纠正了这一点,它对我有用。

Take care all your js errors and warning messages .注意所有js 错误警告消息

This may help to someone.这可能对某人有所帮助。

Something very stupid I did...had 2 Forms on a page with one button on each form.我做了一些非常愚蠢的事情......在一个页面上有 2 个表单,每个表单上有一个按钮。 I had added script to submit a specific form based on the button clicked but, since the default action of a button on a form is to do a submit, it called my Controller Action twice.我添加了脚本以根据单击的按钮提交特定表单,但是,由于表单上按钮的默认操作是提交,因此它两次调用了我的控制器操作。 :^( :^(

    $('#SaveButton').click(function (event) {
        $("#AttendanceDetailForm").submit();
    });

It was old, but some one will need it.它很旧,但有人会需要它。 My problem is style="background-image: url(../) . Let's find html, css code about this style我的问题是style="background-image: url(../) 。让我们找到关于这种风格的 html, css 代码

I was also facing the same issue.我也面临同样的问题。 after thoroughly checking my project , i found none such empty reference case.在彻底检查我的项目后,我没有发现这样的空参考案例。 Then i found out that it is caused by FireBug.然后我发现它是由FireBug引起的。 Disabling firebug or using other browser which has not firebug installed solved the problem.禁用萤火虫或使用其他没有安装萤火虫的浏览器解决了这个问题。

My issue was resolved by making sure I wasn't double referencing my JavaScript files, which I was.通过确保我没有重复引用我的JavaScript文件,我的问题得到了解决。

This was causing the action to be hit twice when I clicked the link.当我单击链接时,这导致操作被击中两次。

I know the above has been said before but I thought I would point out that it's worth checking to see if your files are being loaded twice, especially if you're using Partial Views .我知道之前已经说过以上内容,但我想我会指出,检查您的文件是否被加载两次是值得的,尤其是在您使用Partial Views

I noticed that in one of my Partial Views I was telling it to use the main layout page which contained the scripts that were responsible for what happened when I clicked on the links.我注意到在我的Partial Views之一中,我告诉它使用主布局页面,其中包含负责单击链接时发生的事情的脚本。 So I fixed this by just setting layout = null;所以我通过设置layout = null;解决这个问题layout = null; since it's a partial view anyway and is already being loaded inside of the main layout.因为无论如何它都是局部视图并且已经在主布局内加载。

In my case, I was using a Partial View (so no Form tags) and using an on click handler in JQuery to call a method in the controller via Ajax.就我而言,我使用的是局部视图(因此没有表单标签)并使用 JQuery 中的点击处理程序通过 Ajax 调用控制器中的方法。 But I had declared the button the handler was attached to as type Submit.但是我已将处理程序附加到的按钮声明为类型 Submit。 I forgot to pass in e to my handler function so as to call e.PreventDefault()!!我忘了将 e 传递给我的处理程序函数以便调用 e.PreventDefault() !! So the Controller method was being called twice - once from an ajax call and once for Submit.所以 Controller 方法被调用了两次 - 一次来自 ajax 调用,一次用于提交。 The 2nd time around the parameters were null.参数的第二次为空。 This caused me so much grief.这让我非常伤心。 Such a small thing.这么小的事情。 So small that it was easily overlooked.太小了,很容易被忽视。 Hope this helps someone else.希望这对其他人有帮助。

In my case it was incorrectly configured remote script Yandex.metrika (Google analytics analog).就我而言,它是错误配置的远程脚本 Yandex.metrika(Google 分析模拟)。 This script was presented on each page, so any controller and any action was called twice.这个脚本出现在每个页面上,所以任何控制器和任何动作都会被调用两次。 Check your Ya.metrika settings for more details.检查您的 Ya.metrika 设置以了解更多详细信息。

This is an old question and some answers are still useful.这是一个老问题,有些答案仍然有用。 That is why I am adding a new answer, hoping that will help someone else.这就是为什么我要添加一个新答案,希望能对其他人有所帮助。 For me, I have an app that redirects users back and forth between my domains.对我来说,我有一个应用程序可以在我的域之间来回重定向用户。 Due to some of my recent HttpCookie related work, I had added below line of code:由于我最近的一些 HttpCookie 相关工作,我添加了以下代码行:

httpCookieObject.SameSite = SameSiteMode.Strict;

Turns out the SameSiteMode.Strict causes issues when it comes to cross-origin authentication schemes.结果是 SameSiteMode.Strict 在涉及跨域身份验证方案时会导致问题。 This is Microsoft documentation about it: https://docs.microsoft.com/en-us/aspnet/core/security/authentication/cookie?view=aspnetcore-2.2这是关于它的 Microsoft 文档: https : //docs.microsoft.com/en-us/aspnet/core/security/authentication/cookie?view=aspnetcore-2.2

To strictly enforce a same-site policy of SameSiteMode.Strict, set the MinimumSameSitePolicy.要严格执行 SameSiteMode.Strict 的同站点策略,请设置 MinimumSameSitePolicy。 Although this setting breaks OAuth2 and other cross-origin authentication schemes, it elevates the level of cookie security for other types of apps that don't rely on cross-origin request processing.尽管此设置破坏了 OAuth2 和其他跨域身份验证方案,但它提升了不依赖跨域请求处理的其他类型应用程序的 cookie 安全级别。

So, my solution was that I do not use the SameSiteMode.Strict policy and I am good to go.所以,我的解决方案是我不使用 SameSiteMode.Strict 策略,我很高兴。

I was chasing my problem and found it in here:我正在追寻我的问题并在这里找到它:

Had <div style="width: 200px; height: 200px; background-image: url('\\Asd\\image.jpg')"></div> and problem made \\ character so inside server side code i replaced all \\ with / and it is working as charm.<div style="width: 200px; height: 200px; background-image: url('\\Asd\\image.jpg')"></div>和问题使\\字符所以在服务器端代码中我替换了所有\\ /它正在发挥魅力。

I also had the same problem.我也有同样的问题。 my problem was because of an add-on I installed in the browser.我的问题是因为我在浏览器中安装了一个附加组件。

Check out the add-ons in your browser.在浏览器中查看加载项。

I had same script reference in my View and the _Layout.cshtml.我的视图和 _Layout.cshtml 中有相同的脚本引用。 Removing the reference in either place resolved the issue删除任一地方的引用解决了问题

@Scripts.Render("~/bundles/jqueryval")

I'm using ASP.NET MVC and got the same problem.我正在使用 ASP.NET MVC 并遇到了同样的问题。 In my _Layout.cshtml, there was a deprecated tag "bgsound".在我的 _Layout.cshtml 中,有一个已弃用的标签“bgsound”。 The problem got solved by replacing "bgsound" with "audio".通过用“audio”替换“bgsound”解决了这个问题。 I think some deprecated tags may cause the same problem.我认为一些不推荐使用的标签可能会导致同样的问题。

As far as I know, this issue can have three main reasons.据我所知,这个问题可能有三个主要原因。

  1. You called the controller function twice from the client.您从客户端调用了两次 controller function。 That means: New Request => New Scope => New Controller Instance.这意味着:新请求 => 新 Scope => 新 Controller 实例。 So a debug mark in the controllers constructor should hint on a second call.因此,控制器构造函数中的调试标记应该提示第二次调用。

  2. You're calling twice from a middleware.您从中间件调用了两次。

  class Middleware: IMiddleware {  
    public async Task InvokeAsync(HttpContext context, RequestDelegate next)
    {
        await next(context); //call #1
        await next(context); //call #2
        //This is tricky... base calls might also call the controller function, and those are easily overlooked!
        await base.InvokeAsync(HttpContext context, RequestDelegate next);
    }
  }

  1. You're calling twice from the controller itself:您从 controller 本身调用了两次:
  class SomeController: Controller {  
    public override async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
    {
      await next();//call #1
      await next();//call #2
      //And again... tricky... base calls might also call the controller function, and those are easily overlooked!
      await base.OnActionExecutionAsync(context, next);
    }
  }

However, there might be more reasons to this issue, that i'm just not thinking about at the moment.但是,这个问题可能有更多的原因,我只是暂时没有考虑。 The easiest way to indicate second calls within the same request, is to keep "stepping into" at the end of the first call.在同一请求中指示第二次调用的最简单方法是在第一次调用结束时继续“进入”。 You will automatically end up at the second call at some point.您将在某个时候自动结束第二次通话。

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

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