简体   繁体   中英

Controller actions from ProjectReference

I'm using a ProjectReference in the csproj file pointing to another Asp Core project to reuse the models from there.

<Project Sdk="Microsoft.NET.Sdk.Web">
  <PropertyGroup>
    <TargetFramework>net461</TargetFramework>
    <UserSecretsId>HIDDEN</UserSecretsId>
    <PreserveCompilationContext>true</PreserveCompilationContext>
  </PropertyGroup>

  <ItemGroup>
    <ProjectReference Include="..\..\Project1\Project1.csproj" />
  </ItemGroup>
...
</Project>

But this causes the controller actions from the first project to be available in the second project. It seems like the app.UseMvc in the configure method find all the controllers in the first project.

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

Also, if I have the same name of controller in both projects im getting the following error:

AmbiguousActionException: Multiple actions matched. The following actions matched route data and had all constraints satisfied:

Is there any way block the controller actions from the first project when referencing it? Or maby some option in UseMvc to block it there?

Yes. This is how it works. All the controllers from all available assemblies are collected and then fed into the routing framework. If you don't want the controllers from that project to be referenced, then the simplest and most logical approach is to not reference them. Move the models out into a class library and then reference that class library only, rather than the full MVC project, which includes the controllers and a ton of other stuff that shouldn't necessarily be shared.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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