属性路由和 CreatedAtRoute [英] Attribute Routing and CreatedAtRoute

查看:29
本文介绍了属性路由和 CreatedAtRoute的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am trying to convert my Web Api project to use attribute routing. One thing I am not understanding is the CreatedAtRoute method for a POST request. In my WebApiConfig.cs I used to have a

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

我认为不再需要它而对此进行了评论,但是 CreatedAtRoute 想要路由的名字却找不到.那么如何通过属性路由处理呢?

I commented this out thinking it was no longer needed, but CreatedAtRoute wants the name of the route and cant find it. So how is that handled with attribute routing?

推荐答案

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

Ok...this was easy once you see whats going on. In attribute routing you have to specify the Name of the route to retrieve the resource. So on my GET action it looks like this:

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

然后在 POST 操作中将 CreatedAtRoute 更改为:

And then in the POST action change the CreatedAtRoute from:

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

为此:

return CreatedAtRoute("GetSession", new
        {
            visitorId = session.VisitorId,
            sessionId = session.SessionId
        }, session);

这篇关于属性路由和 CreatedAtRoute的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆