匹配单个特定 url 的自定义路由

问题描述

在我的 mvc 应用程序中,我想动态生成一个特定的 url :

https://myapp.corp.com/.well-kNown/microsoft-identity-association.json

此端点应根据 web.config 文件中的值生成一个文件。所以我创建了这个控制器:

public class HostingController : Controller
{
    // GET: Hosting
    [OutputCache(Duration = 100,varyByParam = "none")]
    public ActionResult MicrosoftIdentityAssociation() => Json(new
    {
        associatedApplications = new[]
            {
            new { applicationId = WebConfigurationManager.AppSettings.Get("ClientId") }
            }
    });
}

我改变了这样的路由配置:

    public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

        routes.MapRoute(
            "Azure domain registration",".well-kNown/microsoft-identity-association.json",new { controller = "Hosting",action= "MicrosoftIdentityAssociation" }
            );

        routes.MapRoute(
            name: "Default",url: "{controller}/{action}/{id}",defaults: new { controller = "Home",action = "Index",id = UrlParameter.Optional }
        );
    }

我希望 url 生成 json,如:

{
  "associatedApplications": [
    {
      "applicationId": "1562019d-44f7-4a9d-9833-64333f52181d"
    }
  ]
}

但是当我定位到 url 时,我收到了 404 错误

怎么了?如何修复?

解决方法

您可以使用路由属性:

    [Route("~/.well-known/microsoft-identity-association.json")]
   [OutputCache(Duration = 100,VaryByParam = "none")]
    public ActionResult MicrosoftIdentityAssociation() 
{
..... your code
}

它在邮递员中进行了测试。

,

Asp.Net MVC 无法创建具有扩展名的路由。我不得不编辑我的 Web.config 以将 MVC 框架插入到这个非常具体的文件中。

特别是:

  <system.webServer>    
    <handlers>
      <add name="Azure domain verifier"
        path=".well-known/microsoft-identity-association.json"
        verb="GET" type="System.Web.Handlers.TransferRequestHandler"
        preCondition="integratedMode,runtimeVersionv4.0" responseBufferLimit="0"
     />
    </handlers>
  </system.webServer>

从现在开始,我可以使用 routeconfig.cs 文件或 [RouteAttribute] 路由到我的自定义控制器操作

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...