ASP.NET:新操作不会';行不通
我已经启动了一个web api项目,我正在尝试向现有控制器添加一个新操作。以下是我的控制器代码和配置:ASP.NET:新操作不会';行不通,asp.net,asp.net-web-api,Asp.net,Asp.net Web Api,我已经启动了一个web api项目,我正在尝试向现有控制器添加一个新操作。以下是我的控制器代码和配置: namespace QAServices.Controllers { public class HomeController : Controller { public ActionResult Index() { ViewBag.Title = "Home Page"; return View(
namespace QAServices.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{
ViewBag.Title = "Home Page";
return View();
}
//[Route("Home/Welcome")] I have also tried this but it doesn't work.
public HttpResponseMessage Welcome()
{
HttpResponseMessage response = new HttpResponseMessage();
response.StatusCode = HttpStatusCode.OK;
return response;
}
public ActionResult ProductPage()
{
return View();
}
}
}
线路图
namespace QAServices
{
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 = "Home", action = "Index", id = UrlParameter.Optional }
);
}
}
}
WebApiConfig
namespace QAServices
{
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// Web API configuration and services
// Configure Web API to use only bearer token authentication.
config.SuppressDefaultHostAuthentication();
config.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType));
// Web API routes
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "{controller}/{action}/{id}",
defaults: new { action = "GET", id = RouteParameter.Optional }
);
}
}
}
当我尝试运行新操作时,出现以下错误:
<Error>
<Message>
No HTTP resource was found that matches the request URI 'http://localhost:1095/Home/Welcome'.
</Message>
<MessageDetail>
No type was found that matches the controller named 'Home'.
</MessageDetail>
</Error>
未找到与请求URI名称匹配的HTTP资源http://localhost:1095/Home/Welcome'.
找不到与名为“Home”的控制器匹配的类型。
我遵循了这些原则,但无法找出问题所在:
StatusCode:200,ReasonPhrase:'OK',版本:1.1,内容:,标题:{}
您的HomeController
只是一个普通的MVC控制器。但是,您得到的响应似乎是WebApi响应。因此,它似乎表明请求正在路由到ApiController
您的项目中是否可能有一个ApiController,它用没有欢迎操作方法的[RoutePrefix(“Home”)]
装饰
另外,如果您混合使用了ApicController和MVC控制器,我将保留默认的WebApiConfig路由模板
api/{Controller}/{id}
,或者至少将其与MVC控制器使用的路由模板区分开来。将公共HttpResponseMessage Welcome()
更改为公共操作结果Welcome()
。在ASP.NET MVC中,控制器操作需要返回ActionResult