我正在尝试从我的API获得任何回复。我已经阅读了很多,但任何方式获得404(无法找到资源。) 这是我的代码
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 });
}
}
我正在使用Google Chrome简单REST客户端进行测试:
粘贴到Google Chrome简单REST客户端:
http://localhost:12345/api/Test
并运行GET =&gt;结果404(未找到资源)
粘贴到Google Chrome简单REST客户端:
http://localhost:12345/api/Login
字段数据和标头无效并运行POST =&gt;结果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'
答案 0 :(得分:0)
您收到的是404,因为未配置路由,并且当您取消注释路由配置时可能会收到错误,因为该代码被调用两次,因此尝试定义具有相同名称的路由两次。
您已经说过,在项目范围内搜索“DefaultApi”只会返回WebApiConfig.cs中的结果。尝试使用相同的“WebApiConfig”搜索来查找多个调用。
或者,看看这些人有相同的问题(重复的路线):