我試圖從我的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