【问题标题】:HttpPost and Authorize leads to Error: Server Error in '/' Application. The resource cannot be foundHttpPost 和 Authorize 导致错误:“/”应用程序中的服务器错误。没有找到您要查的资源
【发布时间】:2017-10-10 19:41:16
【问题描述】:

在我的 ASP.Net (.net 4.7 + MVC5) Web 应用程序中,我有一个操作 Search() 会在授权用户后导致错误。错误如下:

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

找不到资源。

描述:HTTP 404。您正在寻找的资源(或其之一 依赖项)可能已被删除,名称已更改,或者是 暂时不可用。请查看以下 URL 并制作 确保拼写正确。

请求的网址:/搜索

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

动作实现如下:

    [Authorize]
    [Route("Search")]
    [HttpPost]
    public ActionResult Search(SearchViewModels passedQuery)
    {
      //Action working code here
      return View("~/Views/Home/Search.cshtml", passedQuery);
    }

表单提交代码如下:

@using (Html.BeginForm("Search", "Home"))
{
    <div class="form-group">
        @Html.TextBoxFor(m => m.Content, new { @class = "form-control" })<br />
        <button type="submit" class="btn btn-danger">SEARCH</button>
    </div>
}

如果我从操作中取出 [HttpPost],那么在调试模式下,即使在授权用户之后,应用程序也能完美运行(没有引发错误)。但是如果不使用 [HttpPost],代码在生产服务器上什么也不做。

有人可以帮忙吗:

  • 为什么使用 [HttpPost] 时会显示错误消息 [授权]?
  • 何时以及为何使用 [HttpPost]? (我提到了一些帖子和 关于 HttpPost 和 HttpGet 使用的文档,但我仍然 我发现很难掌握他们的概念
    适当的用法 [1], [2])

我对 ASP.Net 和 MVC 开发非常陌生,非常感谢任何帮助。谢谢你。

【问题讨论】:

    标签: asp.net asp.net-mvc-5 http-post


    【解决方案1】:

    返回视图的这一行没有意义:

    return View("~/Views/Home/Search.cshtml", passedQuery);
    

    正确使用时,只需使用视图名称而不是其完整的虚拟路径扩展名,并确保Search方法属于HomeController

    [Authorize]
    public class HomeController : Controller
    {
        [HttpPost]
        public ActionResult Search(SearchViewModels passedQuery)
        {
           return View("Search", passedQuery); // or just return View(passedQuery)
        }
    }
    

    注意AuthorizeAttribute需要满足指定要求的授权用户才能访问该方法,所以在提交已经加载的表单时在POST方法上设置是没有用的。当用户请求基于身份验证角色查看的页面时,您需要在控制器类上指定AuthorizeAttribute,并在允许匿名用户通过的方法上设置AllowAnonymousAttribute

    因此,您的 Search 操作对应该像以下示例一样构建:

    [Authorize]
    public class HomeController : Controller
    {
        // other stuff
    
        [Route("Search")]
        [HttpGet] // getting search page request
        [AllowAnonymous] // allow anonymous users to load search page
        public ActionResult Search()
        {
            return View();
        }
    
        [HttpPost] // posting content using inserted values on form
        [AllowAnonymous] // allow anonymous users to load search page
        public ActionResult Search(SearchViewModels passedQuery)
        {
           return View("Search", passedQuery); // or just return View(passedQuery)
        }
    
        // other stuff
    }
    

    【讨论】:

    • 感谢您的回复。我使用了你分享的技术,但它仍然抛出同样的错误!我需要将 (SearchViewModelspassedQuery) 作为参数传递,因为视图需要这个对象来处理一些事情。如果我在不传递 SearchViewModels 参数的情况下使用带有 [AllowAnonymous] 的“public ActionResult Search()”,那么程序会抛出空异常错误,因为视图需要该参数。
    猜你喜欢
    • 2013-01-20
    • 1970-01-01
    • 1970-01-01
    • 2015-04-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-25
    • 1970-01-01
    相关资源
    最近更新 更多