Asp.Net Web Api 2奇怪的路由行为

时间:2014-08-27 12:37:33

标签: c# asp.net-mvc-routing asp.net-web-api2

我正在使用vs2012并使用" ASP.net Web Api 2"开始了一个新项目。模板。完成编码并开始测试系统。我观察到路由的奇怪行为。如:

以下是我的路线:

config.Routes.MapHttpRoute(
    name: "personRoute",
    routeTemplate: "api/px/{action}/{personid:Guid}",
    defaults: new { controller = "px", personid = RouteParameter.Optional }
);

config.Routes.MapHttpRoute(
    name: "DefaultApi",
    routeTemplate: "api/{controller}/{action}/{id}",
    defaults: new { id = RouteParameter.Optional }
);

这是我的控制器:

public class PxController : ApiController {

    private Configuration.DatabaseContext dbctx = new Configuration.DatabaseContext();

    [HttpGet]
    public IEnumerable<Models.Person> GetAll() {
        return dbctx.Persons.ToArray();
    }

    [ActionName( "op" )]
    [HttpGet]
    public Models.Person ById( Guid personid ) {
        var data = dbctx.Persons.FirstOrDefault( e => e.PersonId == personid );

        if (data == null) {
            throw new HttpResponseException( HttpStatusCode.NotFound );
        }

        return data;
    }

    [ActionName( "op" )]
    [HttpPost]
    public void Insert( [FromBody] Models.Person newPerson ) {
        dbctx.Persons.Add( newPerson );           
        dbctx.SaveChanges();  
    }

    [ActionName( "op" )]
    [HttpPut]
    public void Update( [FromBody]Models.Person eperson ) {          
        var data = dbctx.Persons.FirstOrDefault( e => e.PersonId == eperson.PersonId );

        if (data == null) {
            throw new HttpResponseException( HttpStatusCode.NotFound );
        }

        dbctx.Entry( eperson ).State = System.Data.Entity.EntityState.Modified;
        dbctx.SaveChanges();
    }

    [ActionName( "op" )]
    [HttpDelete]
    public void DeleteById( Guid personid ) {
        var data = dbctx.Persons.FirstOrDefault( e => e.PersonId == personid );

        if (data == null) {
            throw new HttpResponseException( HttpStatusCode.NotFound );
        }

        dbctx.Entry( data ).State = System.Data.Entity.EntityState.Deleted;
        dbctx.SaveChanges();
    }

    #region |:.Extended Queries.:|
    [HttpGet]
    public IEnumerable<RemoteProperty> Properties( Guid personid ) {
        var data = from n in dbctx.RemoteProperties
                   where n.PersonId == personid && n.ParentId == null
                   orderby n.PropertyType.Name
                   select n;

        if (data == null)
            throw new HttpResponseException( HttpStatusCode.NotFound );

        foreach (var rp in data) {
            rp.Details = dbctx.RemoteProperties.SqlQuery( "SELECT * FROM properties WHERE parentid = @parid" ).ToArray();
        }

        return data.ToArray();
    }

    [HttpGet]
    public IEnumerable<Relation> Relations( Guid personid ) {
        var data = from n in dbctx.Relations
                   where n.PersonId == personid
                   select n;

        if (data == null)
            throw new HttpResponseException( HttpStatusCode.NotFound );

        return data.ToArray();
    }
    #endregion

    [NonAction]
    protected override void Dispose( bool disposing ) {

        if (dbctx != null && dbctx is IDisposable) {
            dbctx.Dispose();
        }

        base.Dispose( disposing );
    }

}

这些是查询的Fiddler输出:

http://localhost:49318/api/px/GetAll
/* Works as expected */

http://localhost:49318/api/px/op/dfc737ca-312c-e411-ae3c-78843ccba6ef
/* The requested resource does not support http method 'GET'. */

http://localhost:49318/api/px/op?personid=dfc737ca-312c-e411-ae3c-78843ccba6ef
/* Returns the data with personid, but why the above query fails? */

http://localhost:49318/api/px/properties?personid=dfc737ca-312c-e411-ae3c-78843ccba6ef
/* Returns the data with personid */

http://localhost:49318/api/px/properties/dfc737ca-312c-e411-ae3c-78843ccba6ef
/* No action was found on the controller 'Px' that matches the request */

我的问题是这种行为可能是什么原因?我也不能使用像(因为它们不工作)的路线:

"api/{controller}/{personid}/{action}"

2 个答案:

答案 0 :(得分:1)

尝试使用[Route]属性而不是[Action]属性。

在我的控制器上,我已成功使用以下内容:

[RoutePrefix("api/Demo")] // Sets the base route for actions in this controller
public class DemoController : ApiController
{
    [HttpGet]
    [Route("DemoAction")] // This makes this function map to route http://site/api/Demo/DemoAction
    public IHttpActionResult PerformComplexApiAction(int id)
    {
        ...

可以省略[RoutePrefix],并且可以在每个函数的单个[Route]条目中提供完整路径。

答案 1 :(得分:0)

确定。通过检查整个项目并应用更改(如下所列),我成功地完成了它的工作。所以这就是我所做的:

  • 我使用的是VS2012和web.api模板2.0和.net 4.5。
  • VS2012不支持web.api 2.0,但有更新。
  • 我检查了所有DLL文件引用,意识到其中一些版本错误。
  • 因此我删除了所有引用。
  • 我从NuGet获取Web.api 2.2并安装了所有DLL文件
  • 瞧。它开始起作用了。

对于调试项目,有一个&#34;跟踪&#34; MS提供的装配,我用它。它将跟踪消息放入输出窗口,在路由时执行的操作等等。所以我能够看到发生了什么。 VS 2012更新还不足以让它发挥作用。