修改Abp中Auto API Controllers中 默认生成的 Put、Delete请求

在做公家的项目,有个奇葩的规定,Http请求 不能用PutDelete

怎么在使用Abp,自动生成的Api,全局修改原有规则,将修改、删除都改成Post呢?

只需要,在Host项目的XXXModule类中,重写的PreConfigureServices方法,加上如下代码即可。

HttpMethodHelper.ConventionalPrefixes = new Dictionary<string, string[]>
{
    { "GET", ["GetList", "GetAll", "Get"] },
    { "POST", ["Create", "Add", "Insert", "Post", "Put", "Update", "Delete", "Remove", "Patch"] }
};

运行发现,恭喜您报错了

Microsoft.AspNetCore.Routing.Matching.AmbiguousMatchException: The request matched multiple endpoints. Matches: 

Acme.BookStore.Books.BookAppService.DeleteAsync (Acme.BookStore.Application)
Acme.BookStore.Books.BookAppService.UpdateAsync (Acme.BookStore.Application)

解决方案,可重新实现IConventionalRouteBuilder并替换原有实现context.Services.Replace(ServiceDescriptor.Transient<IConventionalRouteBuilder, CustomConventionalRouteBuilder>());

public class CustomConventionalRouteBuilder : ConventionalRouteBuilder
{
    public CustomConventionalRouteBuilder(IOptions<AbpConventionalControllerOptions> options) : base(options)
    {

    }

    public override string Build(
        string rootPath,
        string controllerName,
        ActionModel action,
        string httpMethod,
        ConventionalControllerSetting? configuration)
    {
        var url = base.Build(rootPath, controllerName, action, httpMethod, configuration);
        if (action.ActionName == "Delete" && httpMethod == "POST")
            return $"{url}/Del";
        return url;
    }
}

如果想指定方法,则。只需要项目中添加Microsoft.AspNetCore.Mvc.CoreNuGet包,可以使用ASP.NET Core的标准属性([HttpPost][HttpGet][HttpPut]……)

posted @ 2025-09-23 10:36  HUGO.CM  阅读(21)  评论(0)    收藏  举报