在带有区域的ASP.NET MVC 5中使用路由属性 [英] Using Route Attributes In ASP.NET MVC 5 With Areas

查看:185
本文介绍了在带有区域的ASP.NET MVC 5中使用路由属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此问题与ASP.NET MVC 5有关.

This question pertains to ASP.NET MVC 5.

我正在尝试通过使用路由属性在URL中使用连字符,但是我没有运气让它起作用. 我正在使用此问题此MSDN博客参考.我想要的URL是:

I'm trying to use hyphens in my URLs by using route attributes, but I'm not having any luck getting it to work. I'm using this question and this MSDN blog reference. This URLs I want to have are:

/my-test/
/my-test/do-something

当我构建项目并在浏览器中打开要测试的页面时,出现404错误.这是我到目前为止的代码:

When I build my project and bring the page I'm testing up in a browser, I'm getting a 404 error. Here is the code I have so far:

// RouteConfig.cs
public class RouteConfig
{
    public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
        routes.MapMvcAttributeRoutes();
        AreaRegistration.RegisterAllAreas();
        ...
    }
}

// MyTestController.cs - NOTE: THIS FILE IS IN AN AREA
[RouteArea("MyTest")]
[RoutePrefix("my-test")]
[Route("{action=index}")]
public class MyTestController : Controller
{
    [Route("~/do-something")]
    public JsonResult DoSomething(string output)
    {
        return Json(new
        {
            Output = output
        });
    }

    [Route]
    public ViewResult Index()
    {
        return View();
    }
}

// Index.cshtml
<script>
    $(document).ready(function () {

        // I'm using an ajax call to test the DoSomething() controller.
        // div1 should display "Hello, World!"
        $.ajax({
            dataType: "json",
            type: "POST",
            url: "/product-management/do-something",
            data: {
                output: "Hello, World!"
            }
        }).done(function (response) {
            $("div1").html(response.output);
        });
    });
</script>
<div id="div1"></div>

创建区域时,创建了一个区域注册文件,并且我的所有路线信息都包含在该文件中,但是根据MSDN博客,我可以删除该文件并完全依赖于路线属性.

When I created the area, an area registration file was created and I had all my route information in that file, but according to the MSDN blog, I can remove that file and rely entirely upon the route attributes.

推荐答案

我知道了.该类需要以下RouteAreaAttribute:

I figured it out. The class needed the following RouteAreaAttribute:

[RouteArea("MyTest", AreaPrefix = "my-test")]
public class MyTestController : Controller
{ 
    ...
}

这也让我删除了区域路线注册文件!

This allowed me to delete the area route registration file too!

这篇关于在带有区域的ASP.NET MVC 5中使用路由属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆