猿问

在asp.net MVC中从url中获取参数

我是初学者,从教程点网站学习教程,这里是链接。


https://www.tutorialspoint.com/asp.net_mvc/asp.net_mvc_controllers.htm 我正在按照它的说明创建一个控制器并从 url 中捕获参数,但它有时会显示问题,当我运行时它会显示空白页有时它会显示错误。


“/”应用程序中的服务器错误。无法找到该资源。描述:HTTP 404。您要查找的资源(或其依赖项之一)可能已被删除、更改名称或暂时不可用。请检查以下 URL 并确保其拼写正确。


请求的网址:/employee/


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


这是我的控制器代码


using System;

using System.Collections.Generic;

using System.Linq;


using System.Web;

using System.Web.Mvc;


namespace MVCControllerDemo.Controllers

{

    public class EmployeeController : Controller

    {

        // GET: Employee



        public ActionResult Search(string name)

        {

            var input = Server.HtmlEncode(name);

            return Content(input);

        }

    }

}

这是 routeConfig.cs


using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.Mvc;

using System.Web.Routing;


namespace WebApplication1

{

    public class RouteConfig

    {

        public static void RegisterRoutes(RouteCollection routes)

        {

            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");


            routes.MapRoute(

                name: "Default",

                url: "{controller}/{action}/{id}",

                defaults: new { controller = "Welcome", action = "Index", id = UrlParameter.Optional }

            );

            routes.MapRoute(

   "Employee", "Employee/{name}", new

   {

       controller = "Employee", action = "Search", name =UrlParameter.Optional }

            );


        }

    }

}


largeQ
浏览 249回答 2
2回答

桃花长相依

您必须在默认之前设置特殊路由。routes.MapRoute(    name: "Employee",    url: "Employee/{name}",    defaults: new { controller = "Employee", action = "Search", name = UrlParameter.Optional });routes.MapRoute(    name: "Default",    url: "{controller}/{action}/{id}",    defaults: new { controller = "Welcome", action = "Index", id = UrlParameter.Optional });

繁星点点滴滴

MapRoute 中的控制器和操作名称区分大小写。因此,员工和员工不匹配。您要么想更改传入的 URL,要么将控制器设置调整为:routes.MapRoute(   "employee", "employee/{name}", new   {       controller = "Employee", action = "Search", name =UrlParameter.Optional }            );        }    }
随时随地看视频慕课网APP
我要回答