c# - 在 ASP.NET MVC 5 中使用区域的路由属性

标签 c# asp.net asp.net-mvc visual-studio

这个问题与 ASP.NET MVC 5 有关。

我试图通过使用路由属性在我的 URL 中使用连字符,但我没有运气让它工作。 I'm using this questionthis MSDN blog reference.我想要的网址是:

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

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

// 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 博客,我可以删除该文件并完全依赖路线属性。

最佳答案

我明白了。该类需要以下 RouteAreaAttribute:

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

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

关于c# - 在 ASP.NET MVC 5 中使用区域的路由属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29804701/

相关文章:

c# - 使用更改的默认打印机设置打印 PDF

c# - 表中的 session 过多导致无法生成新 session

javascript - JavaScript 中的 MVC "~"路径

html - 当我选择一个图像时,如何防止图像列表被重置?

c# - 跨语言消息

c# - 带连接的 linq 查询

c# - 更新面板和 GridView

c# - 使用 Guid 和自定义表名称与 Asp.net Identity 1.1 Alpha 创建自定义实现

c# - 多语言网站性能

c# - 在 asp.net mvc 中更改路由 url