我试图从我的API获得任何响应。我已经阅读了很多,但任何方式得到404(资源无法找到。) 这里是我的代码我做错了什么?尝试从API获得响应
Web.config:
<authentication mode="Forms">
<forms loginUrl="~/Account/Login" defaultUrl="~/Home/Index">
</forms>
</authentication>
的Global.asax.cs
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
GlobalConfiguration.Configure(WebApiConfig.Register);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
WebApiConfig.Register(GlobalConfiguration.Configuration);
}
WebApiConfig.cs
public static void Register(HttpConfiguration config)
{
// Web API configuration and services
// Web API routes
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
// webapi return json
// http://stackoverflow.com/questions/9847564/how-do-i-get-asp-net-web-api-to-return-json-instead-of-xml-using-chrome
config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/html"));
}
ApiController:
public class MyAppApiController : ApiController
{
public HttpResponseMessage Test()
{
return Request.CreateResponse(HttpStatusCode.OK, new { Success = true, bbb = "assssdfv[spld[ssadf[ps" });
}
public HttpResponseMessage Login(LoginViewModel loginVM)
{
var url = this.Url.Link("Default", new { Controller = "AccountController", Action = "Login", model = loginVM});
return Request.CreateResponse(HttpStatusCode.OK, new { Success = true, RedirectUrl = url });
}
}
我使用谷歌浏览器简单的REST客户端来进行测试:
- 运行我的VS以管理员身份
- 调试我的应用程序(本地主机:12345与我的网站打开)
粘贴在谷歌浏览器简单的REST客户端:
http://localhost:12345/api/Test
和运行GET =>导致404(找不到资源)
粘贴在谷歌浏览器辛PLE REST客户端:
http://localhost:12345/api/Login
字段中的数据和标头是无效并运行POST =>导致404(找不到资源)
哪里是错我的代码?
更新:
我已经更新:
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
GlobalConfiguration.Configure(WebApiConfig.Register);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
//removed this: WebApiConfig.Register(GlobalConfiguration.Configuration);
}
,这我的代码,
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
工作 但我仍然得到404错误后 - 但错误的是新的: {"Message":"No HTTP resource was found that matches the request URI 'http://localhost:12345/api/Login'.","MessageDetail":"No type was found that matches the controller named 'Login'."}
我的控制器名称是
myProjApiController :ApiController
但
http://localhost:12345/api/myProjApiController/Login'
结果:
404 No type was found that matches the controller named 'myProjApiController'
你为什么注释掉路由映射?如果路线已经定义好了,它们是什么? – David
由于您已将默认路由注释掉,因此URL的'api'部分不再被识别。而是试试这个:'http:// localhost:12345/Test' – DavidG
如果我取消注释,我已经得到一个附加信息:名为'MS_attributerouteWebApi'的路由已经在路由集合中。路由名称必须是唯一的。例外=( – curiousity