【问题标题】:Custom route that match a single specific url匹配单个特定 url 的自定义路由
【发布时间】:2021-05-08 16:37:58
【问题描述】:

在我的 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 错误。

怎么了?如何解决?

【问题讨论】:

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


    【解决方案1】:

    你可以使用路由属性:

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

    在邮递员中测试过。

    【讨论】:

      【解决方案2】:

      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] 路由到我的自定义控制器操作

      【讨论】:

        猜你喜欢
        • 2020-02-18
        • 2013-06-04
        • 1970-01-01
        • 1970-01-01
        • 2013-07-02
        • 2016-04-29
        • 2014-08-13
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多