![](/img/trans.png)
[英]I'm making ASP .NET MVC application, I'm getting this error when running the project
[英]Getting error when running mvc web application?
我是MVC技術的新手。 運行MVC應用程序時出現錯誤。 我已附上我的代碼和錯誤圖片。 請解決我的問題。
我添加了一個名為Default1Controller.cs
的控制器,該控制器的代碼為
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace MvcApplication1.Controllers
{
public class Default1Controller : Controller
{
public string Index()
{
return "hello";
}
public ActionResult About()
{
return View();
}
}
}
只需在RouteConfig
更改它:
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
對此:
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Default1", action = "Index", id = UrlParameter.Optional }
因為默認情況下,它運行HomeController
。
但是,如果您不想更改RouteConfig
,則可以將控制器重命名為HomeController
或在地址欄中鍵入以下內容:
http://localhost:55416/default1
這里有幾件事需要糾正。
按照約定,初始默認控制器稱為HomeController
。 ASP .NET MVC使用控制器“ Home”的名稱來構建路由。 看一下默認的路由配置:
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
請注意, defaults
線將某些選項映射到主路線。 具體來說,它為控制器名稱和操作名稱提供“默認”值,然后指定id組件是可選的。
在此設置中,如果未指定任何控制器或動作,則默認為Home/Index
。 所以這:
http://localhost/
將默認為以下路線:
http://localhost/Home/Index
但是您的控制器名為Default1Controller
。 因此,您必須執行以下一項操作:
HomeController
(或您的路由配置中的任何名稱); 要么 Default1
而不是Home
; 要么 http://localhost/Default1/Index
此外,您的Index
操作看起來不太正確:
public string Index()
{
return "hello";
}
我不確定框架是否會知道如何處理該字符串。 動作需要返回ActionResult
(或其任何派生類)。 像這樣:
public ActionResult Index()
{
return Content("hello");
}
有可能是在框架中的一些功能,在自動換行的值ContentResult
,我不知道。 但是至少,從語義上講,一致地返回ActionResult
似乎更有意義。 這也將有助於區分MVC控制器和API控制器。
此外,即使該Index
操作確實起作用,或者甚至在使用ContentResult
,它返回的只是一個字符串,而不是實際的頁面。 這是用戶訪問網站時要采取的默認操作嗎?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.