HTTP错误400.0 - 错误请求

时间:2015-12-08 05:28:52

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

我的代码中需要帮助解决ASP.NET MVC 5错误

查看用户详细信息的字符串参数似乎不可用于该方法,即使它在url中,因此该方法返回 HTTP错误400.0 - 错误请求

这是我的RouteConfig.cs

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

        routes.MapRoute(
           name: "Residents",
           url: "{controller}/{action}/{id}",
           defaults: new { controller = "Residents", action = "Details", id ="UserId"}
       );

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

这是方法:

     // GET: Residents/Details/5
    //[ActionName("Resident-details")]
    public ActionResult Details(string username)
    {
        if (string.IsNullOrWhiteSpace(username))
        {
            return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
        }

      ApplicationUser user = db.Users.Where(u => u.UserName.Equals(username, StringComparison.CurrentCultureIgnoreCase)).FirstOrDefault();
            if (user == null)
            {
                return HttpNotFound();
            }
        ViewBag.user = user;

        return View();
    }

这是生成的网址

http://localhost:59686/Residents/Details/8b422e1d-12cf-42c2-8606-32123b3dc577

但它返回一个错误的请求。 即使我这样做     返回内容(用户名) 在方法的早期,它什么都不返回。没有显示任何内容,表明该参数对方法不可见。

我将很感激这个问题的解决方案

由于

2 个答案:

答案 0 :(得分:2)

您的路线配置不正确。您的方法没有名为id的参数,但您仍在路由配置中定义它。

为了解决问题,请更改您的居民路线,如下所示:

routes.MapRoute(
       name: "Residents",
       // only apply route to Residents/Details/your-user-name
       // make sure to use parameter name {username}, like in your method
       url: "Residents/Details/{username}",
       defaults: new { controller = "Residents", action = "Details"}

答案 1 :(得分:0)

因此,MVC的默认模型绑定需要一个int参数来将您的url映射到操作方法参数。

或者您可以使用以下网址: How to make a redirect in PHP?

或其他选项是尝试使用POST方法提交数据,该方法将包含用户名值。