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

查看:291
本文介绍了属性路由和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 }
        );

我对此进行了评论,认为不再需要它了,但是

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天全站免登陆