简体   繁体   English

路由到angular2 / .net核心中的特定ID

[英]Route to specific id in angular2/.net core

I'm having trouble getting routing in Angular2/.Net Core to work properly. 我在Angular2 / .Net Core中路由无法正常工作。

I've started a default .Net Core web project with Angular, and have successfully created a new controller with the applicable view components. 我已经使用Angular启动了一个默认的.Net Core Web项目,并成功创建了具有适用视图组件的新控制器。 The page's purpose is to display a list of documents and give you the option to click the title to see each document in a separate view. 该页面的目的是显示文档列表,并使您可以单击标题以在单独的视图中查看每个文档。

So long everything works, it displays the contents of the page and I can also display a list of documents retrieved from the database. 只要一切正常,它就会显示页面的内容,我还可以显示从数据库中检索到的文档列表。 The routing looks like this: 路由如下所示:

@NgModule({
    declarations: [
        AppComponent,
        NavMenuComponent,
        DocumentsComponent,
        HomeComponent
    ],
    imports: [
        CommonModule,
        HttpModule,
        FormsModule,
        RouterModule.forRoot([
            { path: '', redirectTo: 'home', pathMatch: 'full' },
            { path: 'home', component: HomeComponent },
            { path: 'documents', component: DocumentsComponent },
            { path: '**', redirectTo: 'home' }
        ])
    ]
})
export class AppModuleShared {
}

I have a link on each document so that when you click it you are transferred from the list /documents to eg. 我在每个文档上都有一个链接,以便单击时将其从列表/documents转移到例如。 /documents/1

When I click on a link it only stays there long enough so I can see the URL change and then it goes to the default fallback /home . 当我单击链接时,它仅停留了足够长的时间,因此我可以看到URL更改,然后转到默认的后备/home

In Startup.cs I have the default route handling set: 在Startup.cs中,我设置了默认的路由处理:

app.UseMvc(routes =>
{
    routes.MapRoute(
        name: "default",
        template: "{controller=Home}/{action=Index}/{id?}");
    routes.MapSpaFallbackRoute(
        name: "spa-fallback",
        defaults: new { controller = "Home", action = "Index" });
});

From what I can tell the "default" map route should pick up /documents/1 but it doesn't. 据我所知,“默认”地图路由应选择/documents/1但不能。 I never even gets to the backend method for the route. 我什至从未接触过该路线的后端方法。

[Produces("application/json")]
[Route("api/[controller]")]
public class DocumentsController : Controller
{
    private readonly DatabaseContext _context;

    public DocumentsController(DatabaseContext context)
    {
        _context = context;
    }

    // GET: api/Documents
    [HttpGet]
    public IActionResult GetDocuments()
    {
        // returns a JSON list of documents, works fine
    }

    // GET: api/Documents/5
    [HttpGet("{id}")]
    public async Task<IActionResult> GetDocument([FromRoute] int id)
    {
        //returns the specified document, is never even called
        if (!ModelState.IsValid)
        {
            return BadRequest(ModelState);
        }

        var document = await _context.Documents.SingleOrDefaultAsync(m => m.Id == id);

        if (document == null)
        {
            return NotFound();
        }

        return Ok(document);
    }

What do I need to do to get the specific routes to work? 我需要做什么才能使特定的路线起作用?

From what I can tell the "default" map route should pick up /documents/1 but it doesn't. 据我所知,“默认”地图路由应选择/documents/1但不能。

Nope. 不。 The default route isn't configured that way. 默认路由未采用这种方式配置。 You must supply the action method name as the second parameter to match the default route. 您必须提供操作方法名称作为第二个参数,以匹配默认路由。

/documents/getdocument/1

That said, it won't work. 就是说,这行不通。 When you add an attribute route it automatically blocks the above route. 添加属性路由时,它会自动阻止上述路由。

Therefore, the only URL that will work to get to DocumentsController.GetDocument(int) is: 因此,唯一可以访问DocumentsController.GetDocument(int) URL是:

/api/documents/1

This is because you are defining [Route("api/[controller]")] on your controller which makes every action in the controller prefixed this way. 这是因为您要在控制器上定义[Route("api/[controller]")] ,从而使控制器中的每个操作都以此方式为前缀。

If you want /documents/1 to be the URL and use attribute routing, you can use: 如果希望/documents/1作为URL并使用属性路由,则可以使用:

[Produces("application/json")]
[Route("documents")]
public class DocumentsController : Controller
{
    private readonly DatabaseContext _context;

    public DocumentsController(DatabaseContext context)
    {
        _context = context;
    }

    // GET: api/Documents
    [HttpGet(Order = 2)]
    public IActionResult GetDocuments()
    {
        // returns a JSON list of documents, works fine
    }

    // GET: api/Documents/5
    [HttpGet("{id}", Order = 1)]
    public async Task<IActionResult> GetDocument([FromRoute] int id)
    {
        //returns the specified document, is never even called
        if (!ModelState.IsValid)
        {
            return BadRequest(ModelState);
        }

        var document = await _context.Documents.SingleOrDefaultAsync(m => m.Id == id);

        if (document == null)
        {
            return NotFound();
        }

        return Ok(document);
    }
}

Or if you want to use convention based routing, remove the [Route] attribute from the controller, URL templates and Order from HttpGet above each action method and use: 或者,如果您想使用基于约定的路由,请从控制器,URL模板和HttpGet OrderHttpGet每种操作方法上方的[Route]属性,并使用:

app.UseMvc(routes =>
{
    routes.MapRoute(
        name: "documents",
        template: "documents/{id?}",
        defaults: new { controller = "Documents", action = "GetDocuments" });

    routes.MapRoute(
        name: "default",
        template: "{controller=Home}/{action=Index}/{id?}");
});

You need to tell the angular router that there is more after the documents part of the path. 您需要告诉角度路由器,路径的documents部分之后还有更多documents It's looking for a component matched to the route /documents/1 and not finding it. 它正在寻找与路由/documents/1匹配的组件,但找不到它。 If you add /:id to your path it should allow it to map the second part of your url to a route instead of redirecting to home 如果将/:id添加到路径,则应允许其将网址的第二部分映射到路由,而不是重定向到home

{ path: 'documents/:id', component: DocumentsComponent },

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM