4

我有一个简单的表单,它发布到一个HttpPost操作方法,该方法返回其相应的视图。我的问题是我遇到了404 Not Found错误。奇怪的是,如果我将表单方法和 action 方法的属性更改为 a GET,那么它可以工作并显示 TestMethod 视图。

似乎我缺少使用的东西POST,但我在其他控制器中的帖子工作正常(例如帐户登录和注册)。请注意,该AllowAnonymous属性是一个自定义属性,能够指定允许匿名访问的控制器或操作,而不是指定(通过Authorizeattr)需要授权的控制器或操作。我想没有什么是不可能的,但我认为这与我的问题无关。对出了什么问题有任何想法吗?

形式:

@using (Html.BeginForm("TestMethod", "Test", FormMethod.Post, new { @id = "testForm" })) {
    <fieldset>
        <legend>Test Form</legend>
        <input type="submit" value="Submit" />
    </fieldset>
}

控制器动作:

[AllowAnonymous]
[HttpPost]
public ActionResult TestMethod() {
    return View();
}

看法:

<h2>TestMethod</h2>
<p>HttpPost method was successful.</p>

从 Global.asax.cs 注册路由方法:

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

        // About
        routes.MapRoute(
            "About", // Route name
            "about", // URL with parameters
            new { controller = "Home", action = "About" } // Parameter defaults
        );

        // Faq
        routes.MapRoute(
            "Faq", // Route name
            "faq", // URL with parameters
            new { controller = "Home", action = "Faq" } // Parameter defaults
        );

        // Glossary
        routes.MapRoute(
            "Glossary", // Route name
            "glossary", // URL with parameters
            new { controller = "Home", action = "Glossary" } // Parameter defaults
        );

        // Register
        routes.MapRoute(
            "Register", // Route name
            "register", // URL with parameters
            new { controller = "Account", action = "Register" } // Parameter defaults
        );

        // LogIn
        routes.MapRoute(
            "LogIn", // Route name
            "login/{id}", // URL with parameters
            new { controller = "Account", action = "LogOn", id = UrlParameter.Optional } // Parameter defaults
        );
        routes.MapRoute(
            "LogOn", // Route name
            "logon/{id}", // URL with parameters
            new { controller = "Account", action = "LogOn", id = UrlParameter.Optional } // Parameter defaults
        );

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

}

授权属性代码:

// AllowAnonymousAttribute class
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false, Inherited = true)]
public sealed class AllowAnonymousAttribute : Attribute { }

// GlobalAuthorize class
public sealed class GlobalAuthorize : AuthorizeAttribute {
    public override void OnAuthorization(AuthorizationContext filterContext) {
        bool skipAuthorization = 
            filterContext.ActionDescriptor.IsDefined(typeof(AllowAnonymousAttribute), true) || 
            filterContext.ActionDescriptor.ControllerDescriptor.IsDefined(typeof(AllowAnonymousAttribute), true);

        if (!skipAuthorization) base.OnAuthorization(filterContext);
    }
}

// RedirectAuthorizeAttribute class
public class RedirectAuthorizeAttribute : AuthorizeAttribute {
    public string RedirectUrl { get; set; }

    protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext) {
        filterContext.Result = new RedirectResult(RedirectUrl);
    }
}

全局过滤器:

public static void RegisterGlobalFilters(GlobalFilterCollection filters) {
    filters.Add(new RequireHttpsAttribute());
    filters.Add(new GlobalAuthorize());
    filters.Add(new HandleErrorAttribute());
}

路线改写规则:

<rewrite>
  <rules>
    <!-- Block all requests made to a website that do not have the host header set. -->
    <rule name="Fail bad requests" stopProcessing="true">
      <match url=".*" />
      <conditions>
        <add input="{HTTP_HOST}" pattern="localhost" negate="true" />
      </conditions>
      <action type="AbortRequest" />
    </rule>
    <!-- Remove trailing slash from all incoming requests. -->
    <rule name="Remove trailing slash" stopProcessing="false">
      <match url="(.*)/$" />
      <conditions>
        <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
        <add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" />
      </conditions>
      <action type="Redirect" redirectType="Permanent" url="{R:1}" />
    </rule>
    <!-- Convert all requests to all lowercase. -->
    <rule name="Convert to lowercase" stopProcessing="false">
      <match url=".*[A-Z].*" ignoreCase="false" />
      <action type="Redirect" url="{ToLower:{R:0}}" redirectType="Permanent" />
    </rule>
    <!-- Any URL with (HTTPS == OFF) and (HTTP_HOST with colon) -> use for development testing. -->
    <rule name="Development redirect to HTTPS" enabled="true" stopProcessing="true">
      <match url=".*" ignoreCase="true" />
      <conditions logicalGrouping="MatchAll" trackAllCaptures="true">
        <add input="{HTTPS}" pattern="^OFF$" />
        <add input="{HTTP_HOST}" pattern="([^/:]*?):[^/]*?" />
      </conditions>
      <action type="Redirect" url="https://{C:1}:44300{URL}" />
    </rule>
    <!-- Redirect any HTTP request to HTTPS. -->
    <rule name="Redirect to HTTPS" stopProcessing="true">
      <match url="(.*)" />
      <conditions>
        <add input="{HTTPS}" pattern="^OFF$" ignoreCase="true" />
      </conditions>
      <action type="Redirect" url="https://{HTTP_HOST}/{R:1}" redirectType="Permanent" />
    </rule>
  </rules>
</rewrite>
4

2 回答 2

5

我想我终于找到了罪魁祸首。首先,我承认,现在知道问题出在哪里,这个问题的标题不是很准确。该问题主要与 Web.config 中的规则重写有关。在回复其他人对这个问题的评论之前,我完全忘记了规则重写,这就是为什么我一开始没有进一步检查它们的原因。

无论如何,问题在于将 URL 重写为全部小写的规则。我知道我的帐户注册和登录表单工作正常,所以我检查了它们并注意到它们的Html.BeginForm语句是无参数的,这显然会导致生成一个小写的 url。我为我的测试方法尝试了无参数的 POST 请求,它起作用了。然后,我尝试在Html.BeginForm语句中使用 action 和 controller 的参数,但这次我将它们输入为小写字符串:Html.BeginForm("testmethod", "test"...). 果然,它也可以正常工作,并且页面源将表单操作显示为小写。

为了解决我的问题,我只需要设置一个不匹配POST请求的条件:<add input="{REQUEST_METHOD}" matchType="Pattern" pattern="POST" negate="true" />. 请注意,问题不是具体的小写规则,而是POST请求被重定向。我发现一篇博客讨论了POST重定向被转换为GETs 并导致错误的问题,这正是我所经历的。它已经有几年的历史了,但显然它仍然是相关的信息。

无论如何,我现在已经恢复正常运行了。感谢所有投入两分钱的人。

PS 当我关闭浏览器选项卡并结束搜索时,我想我会链接到这个 SO question,因为它肯定与我的问题有关。

于 2012-08-20T21:37:57.453 回答
0

我刚才测试了你的代码。我最初因为不使用 HTTPS 而被重定向,所以我禁用了这个属性,但之后你的代码就可以工作了。

这是我的逻辑推论...

  • 如果 HTTPS 是问题所在,您将不会收到 404。
  • 如果您没有登录,您将被重定向到登录页面。

我能想到的唯一一件事是您的控制器要么没有命名为“TestController”,要么您的控制器在一个区域中,而您忘记为该区域提供BeginForm. 它是其中之一吗?

于 2012-08-20T09:37:47.057 回答