我有MVC项目,我添加了一个API控制器。在这个API控制器中,我已经在其中创建了方法。但是当我尝试使用" http://localhost:10133/api/BedfordBrownstoneApi/GetAgentId?username=dgsdgsdgsd&password=sdgsdgs&从postman或localhost调用此API时#34; Url给出了以下回复。
{
"Message": "No HTTP resource was found that matches the request URI 'http://localhost:10133/api/BedfordBrownstoneApi/GetAgentId?username=dgsdgsdgsd&password=sdgsdgs'.",
"MessageDetail": "No type was found that matches the controller named 'BedfordBrownstoneApi'."
}
我的API控制器如下所示。
public class BedfordBrownstoneApi : ApiController
{
// GET api/<controller>
public int GetAgentId(string username,string password)
{
DataContext db = new DataContext();
var data = db.Set<AgentLogin>().Where(a => a.UserName==username && a.Password==password).SingleOrDefault();
return data.AgentId;
}
}
}
我的WebApiConfig类如下。
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{action}",
defaults: new { action = "GetAgentId" }
);
}
}
答案 0 :(得分:0)
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{action}/{id}",
defaults: new { action = "GetAgentId",id = RouteParameter.Optional }
);
在webapiconfig中的routeTemplete中添加Id参数。
答案 1 :(得分:0)
检查以下问题与您的问题类似。
检查&#39; Benoit74B&#39;的接受答案。它清楚地解释了问题的细节。实际问题与您传递的参数有关 -
"No HTTP resource was found that matches the request URI" here?
答案 2 :(得分:0)
从控制器名称BedfordBrownstoneApi中删除“API”。
从
更改http://localhost:10133/api/BedfordBrownstoneApi/GetAgentId?username=dgsdgsdgsd&password=sdgsdgs
到
http://localhost:10133/api/BedfordBrownstone/GetAgentId?username=dgsdgsdgsd&password=sdgsdgs
答案 3 :(得分:0)
您是否在api配置中启用了属性路由? config.MapHttpAttributeRoutes();
根据您当前的路线,您应该通过查询字符串&#34; http://localhost:10133/api/BedfordBrownstoneApi/GetAgentId?username=dgsdgsdgsd&password=sdgsdgs&#34;并用[FromUri]
[HttpGet]
[Route("api/BedfordBrownstoneApi/GetAgentId/")]
public int GetAgentId(string username,string password)
{
//api stuff
}
或通过路线参数点击api - http://localhost:10133/api/BedfordBrownstoneApi/GetAgentId/yourusername/yourpassword
[HttpGet]
[Route("api/BedfordBrownstoneApi/GetAgentId/{username}/{password}")]
public int GetAgentId(string username,string password)
{
//api stuff
}
希望这会对你有所帮助。谢谢!
答案 4 :(得分:0)
有两个问题。
请更新您的注册信息&#39;功能于WebApiConfig&#39;如下。
public static void Register(HttpConfiguration config)
{
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{action}",
defaults: new { action = "GetAgentId" }
);
}
答案 5 :(得分:0)
我刚刚将代码更改为以下内容,现在已将其工作。
public static void Register(HttpConfiguration config)
{
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "BedfordBrownstoneApi",
routeTemplate: "api/{controller}/{action}",
defaults: new { action = "GetAgentId" }
);
}