网页 Api。找到多个与请求匹配的操作。如何添加自定义端点

Web Api. Multiple actions were found that match the request. How to add custom endpoint

我有带有 CRUD 的休息 Web Api 控制器。我需要添加自定义 POST 端点:

public class TherapistController : ApiController
    {
       public IHttpActionResult Post(TherapistModel therapistModel)
        {
           return Ok(therapist);
        }

        public IHttpActionResult SendConfirmationEmail(TherapistModel therapistModel)
        {
            return Ok(therapist);
        }
    }

但在这种情况下我有一个错误:"Multiple actions were found that match the request"。

这是网络Api配置:

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

这是我的 API 电话:

axios({
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            url: '/internal/api/therapist/',
            data: this.state.newTherapist
        });

 axios({
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            url: '/internal/api/Therapist/SendConfirmationEmail/',
            data: this.state.newTherapist
        });
axios({
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        url: '/internal/api/therapist/', // remove '/' from last form both url
        data: this.state.newTherapist
    });

我建议在这些情况下使用属性路由,因为您对同一个 http 动词有多个操作方法。

下面会起作用,

在 Register 方法中所有定义的路由上方添加此行

config.MapHttpAttributeRoutes(); // 启用属性路由 Web API routes

并将路由定义为属性..

[RoutePrefix("internal/api/therapist")]
public class TherapistController : ApiController
{
    [HttpPost]
    [Route("Post/{therapistModel}")]
    public IHttpActionResult Post(TherapistModel therapistModel)
    {
        return Ok();
    }

    [HttpPost]
    [Route("Email/{therapistModel}")]
    public IHttpActionResult SendConfirmationEmail(TherapistModel therapistModel)
    {
        return Ok();
    }
}

在你的JS调用代码中..

internal/api/therapist/post/{你的参数}

internal/api/therapist/email/{你的参数} ....相应地调用上述方法