我正在研究带有属性路由的Asp.Net MVC 5 Web API项目。我有一个使用RoutePrefix和Route的国家/地区控制器。如果我确实请求不带参数的方法或以模型为参数的方法,则效果很好。
例如,我请求
AddorEdit
使用Country model
中的http://localhost/api/Master/Country/AddOrEdit
的方法,
和
GetAll
中的 http://localhost/api/Master/Country/GetAll
方法
这项工作并返回结果。
但是,如果我使用string参数调用方法,则该方法无效。 例如,
如果我拨打电话
Get/{transId}
来自http://localhost/api/Master/Country/Get/1
Get/{transId}
来自http://localhost/api/Master/Country/Get/?transId=1
Get/{transId}
来自http://localhost/api/Master/Country/Get?transId=1
,
这不起作用。这将产生以下错误:
<Error>
<Message>
No HTTP resource was found that matches the request URI 'http://localhost:11035/api/Master/Country/Get/449cc9b8-81b3-4b7e-8561-b98cf39d9492'.
</Message>
<MessageDetail>
No action was found on the controller 'Country' that matches the request.
</MessageDetail>
</Error>
我还检查了HTTP动词并应用了2个动词。另外,从Postman发出POST
请求,但仍然收到相同的错误。
我曾经尝试过Google等,但没有运气。我还添加了默认路由规则,仍然没有运气。
路由代码
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{action}/{transId}",
defaults: new { transId = RouteParameter.Optional }
);
控制器代码
[RoutePrefix("api/Master/Country")]
public class CountryController : BaseApiController
{
[Route("AddOrEdit")]
[HttpPost]
public IHttpActionResult AddOrEdit(Country country)
{
try
{
using (ApplicationDbContext dbContext = new ApplicationDbContext())
{
var _country = dbContext.Country.Where(x => x.TransID.Equals(country.TransID)).FirstOrDefault();
if(null == _country)
dbContext.Country.Add(country);
else
{
_country.Code = country.Code;
_country.Name = country.Name;
_country.Description = country.Description;
_country.IsDeleted = country.IsDeleted;
}
dbContext.SaveChanges();
}
return Ok();
}
catch (Exception e)
{
return InternalServerError(e);
}
}
[Route("Get/{ transId }")]
[HttpGet, HttpPost]
public IHttpActionResult GetCountryResult(string transId)
{
Country data;
try
{
using (ApplicationDbContext dbContext = new ApplicationDbContext())
{
data = dbContext.Country
.Where(x => x.TransID.Equals(new Guid(transId)))
.FirstOrDefault();
}
return Ok(data);
}
catch (Exception e)
{
return InternalServerError(e);
}
}
[Route("GetAll")]
[HttpGet]
public IHttpActionResult GetCountryResults()
{
List<Country> lidata;
try
{
using (ApplicationDbContext dbContext = new ApplicationDbContext())
{
lidata = dbContext.Country.ToList();
}
return Ok(lidata);
}
catch (Exception e)
{
return InternalServerError(e);
}
}
}
答案 0 :(得分:0)
尝试删除路线中transId的多余空格
例如:
对此[Route("Get/{ transId }")]
感兴趣,请尝试此[Route("Get/{transId}")]
查看路线差异
[Route("Get/{transId}")]
[HttpGet, HttpPost]
public IHttpActionResult GetCountryResult(string transId)
{
Country data;
try
{
using (ApplicationDbContext dbContext = new ApplicationDbContext())
{
data = dbContext.Country
.Where(x => x.TransID.Equals(new Guid(transId)))
.FirstOrDefault();
}
return Ok(data);
}
catch (Exception e)
{
return InternalServerError(e);
}
}