【问题标题】:api coming twice in URL "api/AuthenticationAPI/logout"api 在 URL“api/AuthenticationAPI/logout”中出现两次
【发布时间】:2019-10-16 06:13:18
【问题描述】:

作为我们项目中的约定,我们将所有 API 控制器类命名为 AuthenticationApiController,而不是 MVC 中的控制器 AuthenticationController

但是现在当 API 被调用时,我们必须像 /api/authenticationapi/logout 这样调用它。

认为没问题,但我不喜欢 URL 中出现两次“api”字样。

有没有办法,我可以自定义定义为[Route("api/[controller]")] 的路由,以便在将 URL 添加到路由表时从控制器名称中删除 api。

**注意:寻找通用方式,而不是在每个 api 控制器上硬编码名称。

【问题讨论】:

  • 当然可以。您可以将其添加到控制器功能并使用该 url 发出请求。
  • 但是那不会是通用的......在这里我创建了一个 BaseApiController 并从中派生了所有控制器......所以我不必在所有控制器上都这样做
  • 那么..添加控制器有两种方式:webapiController(这个使用api/~)和MVC控制器(不包括api)
  • 你也可以设置WebApiConfig.cs

标签: asp.net-mvc asp.net-core routing


【解决方案1】:

尝试使用Url Rewriter并参考我使用asp.net core 3.0的演示:

1.创建重写器规则

public class RewriteRules
{
    public static void ReWriteRequests(RewriteContext context)
    {
        var request = context.HttpContext.Request;
        var path = request.Path.Value;

        if (path != null)
        {
            var array = path.Split("/");
            if (array[1] == "api" && !array[2].EndsWith("api", StringComparison.OrdinalIgnoreCase))
            {
                array[2] = array[2] + "api";
                var newPath = String.Join("/", array);
                context.HttpContext.Request.Path = newPath;

            }
        }

    }
}

2.在启动Configure方法中注册(如果你使用core 2.2,在app.UseMvc()之前)

app.UseRewriter(new RewriteOptions()
            .Add(RewriteRules.ReWriteRequests)
            );
app.UseRouting();         
app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllerRoute(
                name: "default",
                pattern: "{controller=Home}/{action=Index}/{id?}");
        });

3.测试

[Route("api/[controller]")]
[ApiController]
public class AuthenticationApiController : ControllerBase
{
    // GET: api/TestApi
    [HttpGet("logout")]
    public IEnumerable<string> logout()
    {
        return new string[] { "value1", "value2" };
    }
 }

调用/api/authentication/logout会成功进入动作

【讨论】:

    猜你喜欢
    • 2020-02-17
    • 1970-01-01
    • 1970-01-01
    • 2020-01-22
    • 2017-04-29
    • 1970-01-01
    • 1970-01-01
    • 2018-04-16
    • 1970-01-01
    相关资源
    最近更新 更多