我正在创建一个名为"客户"的新的Web API控制器。该控制器有一个名为"创造"
的动作我无法通过" get" http请求来要求此操作以这种形式
http://ip:port/api/customer/create?userId = x& password = y
在此方法中除外:
public class CustomerController : ApiController
{
[System.Web.Mvc.AcceptVerbs("GET", "POST")]
[System.Web.Mvc.HttpGet]
[ActionName("Create")]
public MISApiResult<List<Branch>> GetCreate(string userID, string password)
{
return new MISApiResult<List<Branch>>() { Result = new List<Branch>() { new Branch() { ID = Guid.NewGuid(), Name = "Branch1" } }, ResultCode = 1, ResultMessage = "Sucess" };
}
}
是否还有其他解决方案将动作名称保存为"创建"的下一步。
public class CustomerController : ApiController
{
[System.Web.Mvc.AcceptVerbs("GET", "POST")]
[System.Web.Mvc.HttpGet]
public MISApiResult<List<Branch>> Create(string userID, string password)
{
return new MISApiResult<List<Branch>>() { Result = new List<Branch>() { new Branch() { ID = Guid.NewGuid(), Name = "Branch1" } }, ResultCode = 1, ResultMessage = "Sucess" };
}
}
谢谢。
编辑:
很抱歉第一次没有清楚。
根据此答案:
MVC WebAPI中的方法如何映射到http动词?
根据操作名称有一个默认的http方法,如果它以get get为单位,则默认情况下它会默认地获取http方法,否则将映射到发布。
是否有一种方法可以使用自定义映射来更改此默认映射,以便我可以映射一个名为"创建"的动作,其中" get" http方法用于测试目的,因为这种方式对于开发而言更快
我试图将httpget属性和acceptverbs(" get"(放置,并且它仍然使用http http方法映射动作。
我找到了一种像我所说的那样的方式,它是将动作方法名称更改为GetCreate,然后将ActionName属性放入"创建"值。但是,有没有办法更改默认映射?
再次感谢。
您可以使用自定义路由此操作:
[HttpGet]
[Route("customer/create")]
public MISApiResult<List<Branch>> Create(string userID, string password)
不要忘记在应用程序配置期间启用属性路由(应在默认路由定义之前添加此内容(:
config.MapHttpAttributeRoutes();
尽管我建议遵循约定并使用适当的http动词 - 如果您创建客户,则通过"惯例",您应该使用发布请求来端点 api/customers 。否则,您的API可能会使其他人感到困惑。
我也建议将IHttpActionResult
用作您方法的返回类型:
public IHttpActionResult Post(string userID, string password)
{
if (_userRepository.Exists(userID))
return BadRequest($"User with ID {userID} already exists");
_userRepository.Create(userID, password);
return StatusCode(HttpStatusCode.Created) // or CreatedAtRoute
}
进一步读取:ASP.NET Web API中的属性路由2
为什么不指定路由。您的实际问题是使用System.Web.Mvc
使用System.Web.Http
而改用
using System.Web.Http;
[RoutePrefix("api/Customer")]
public class CustomerController : ApiController
{
[HttpGet]
[Route("Create")]
public MISApiResult<List<Branch>> Create(string userID, string password)
{
return new MISApiResult<List<Branch>>() { Result = new List<Branch>() { new Branch() { ID = Guid.NewGuid(), Name = "Branch1" } }, ResultCode = 1, ResultMessage = "Sucess" };
}
}