属性路由和CreatedAtRoute

Mik*_*e_G 11 c# asp.net-web-api asp.net-web-api-routing

我正在尝试将我的Web Api项目转换为使用属性路由.我不理解的一件事是POST请求的CreatedAtRoute方法.在我的WebApiConfig.cs中,我曾经有过

config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/account/{accountId}/site/{siteId}/visitor/{visitorId}/session/{sessionId}/{controller}/{action}",
            defaults: new { action = RouteParameter.Optional }
        );
Run Code Online (Sandbox Code Playgroud)

我评论说这不再需要它,但CreatedAtRoute想要路线的名称而无法找到它.那么如何处理属性路由呢?

Mik*_*e_G 27

好的...一旦你看到最新情况,这很容易.在属性路由中,您必须指定要检索资源的路由的名称.所以在我的GET操作上它看起来像这样:

[Route("{sessionId}",Name="GetSession")]
    [ResponseType(typeof(Session))]
    public async Task<IHttpActionResult> Get(HttpRequestMessage request, int accountId, int siteId, Guid visitorId, Guid sessionId)
Run Code Online (Sandbox Code Playgroud)

然后在POST操作中更改CreatedAtRoute:

return CreatedAtRoute("DefaultApi", new
        {
           controller: "session"
            visitorId = session.VisitorId,
            sessionId = session.SessionId
        }, session);
Run Code Online (Sandbox Code Playgroud)

对此:

return CreatedAtRoute("GetSession", new
        {
            visitorId = session.VisitorId,
            sessionId = session.SessionId
        }, session);
Run Code Online (Sandbox Code Playgroud)