我已经启动了一个web api项目,我正在尝试向现有控制器添加一个新动作。这是我的控制器代码和配置:
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();
}
}
}
RouteConfig
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>
我已经按照这些但无法弄清楚出了什么问题:
答案 0 :(得分:1)
您的代码适合我。我收到了回复StatusCode: 200, ReasonPhrase: 'OK', Version: 1.1, Content: , Headers: { }
。
你的HomeController
只是一个普通的MVC控制器。但是,您获得的响应似乎是WebApi响应。所以它似乎表明请求被路由到ApiController。
您的项目中是否有可能使用[RoutePrefix("Home")]
装饰但没有Welcome
操作方法的ApiController?
此外,如果您混合使用ApiController和MVC Controller,我会保留默认的WebApiConfig路由模板api/{controller}/{id}
,或至少区别于用于MVC控制器的模板。
答案 1 :(得分:0)
将public HttpResponseMessage Welcome()
更改为public ActionResult Welcome()
。在ASP.NET MVC控制器中,操作需要返回ActionResult。