Call controllers from one project to another project - asp.net-mvc

I'm using Asp.net MVC4 with razor. I want to know how to call a controller from one project to another project in a same solution. (I'm new to MVC4)

You can simply add your controllers to another project (class lib or MVC project, etc...) We have a couple projects that share controllers(webAPI as well as MVC). I typically use area constraints for the API controllers and namespace constraints for MVC controllers- especially if you have something like a base HomeController.cs used for some projects and you want to override it in just one particular MVC application project.
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional },
namespaces: new[] { "Common.MVC.Controllers" }
);

The answer depends a great deal on the concrete problem you are trying to solve.
This is something important to remember when asking questions on Stack Overflow. Sometimes it's more beneficial to ask how to solve your problem rather than how to accomplish the solution you've come up with.
If your goal here is to avoid code replication the simplest answer is to add your second project as a reference to your first. Accessing the controller is still a bit difficult because you need to instantiate it properly so what I'd recommend instead is that you abstract the code you wish to avoid replicating into a third project and have both your MVC projects make calls to the utility class you've created.
Another possibility is that you'd like to have your web services interact with each other while maintaining a client/server relationship. This can be achieved by creating an HTTP web request directed at the port number that Visual Studio selects when you run the second web service project. .Net is capable of doing this but personally I recommend using RestSharp.

You have to seperate projects (because you are testing in local) and then run Destination project and get address (like http://localhost:15823/). After that,
in another project's controller, use the following:
public ActionResult Index()
{
return Redirect("http://localhost:15823/");
}
and run another project.

I kept running my other project whose links I was calling. So in short both applications must be running simultaniously.

Related

Web application in ASP.NET 5

I am building a Web Application in ASP .NET 5 using Visual Studio 2015. I have created a solution with Data Access, Business, Services and User Interface layers.
I have referenced the Services in User Interface layer.Since in MVC 6 both Web API and MVC fall under the same project template, it is necessary to have two different layers for services and UI or same project with different controllers is enough.?
And also in the UI project I have uncommented the following lines in Startup.cs
services.AddWebApiConventions();
routes.MapWebApiRoute("DefaultApi", "api/{controller}/{id?}");
While running the project, the home page comes up fine but when I click on links in the home page the url changes like this
http://localhost:45075/api/Home
And it gives error page saying that
AmbiguousActionException: Multiple actions matched. The following actions matched route data and had all constraints satisfied.
Sample.Services.Controllers.HomeController.Index
Sample.Services.Controllers.HomeController.About
Sample.Services.Controllers.HomeController.Contact
Sample.Services.Controllers.HomeController.Error
My understanding is that since I enabled Web Api conventions, it is going to the Home Controller of services which has route attribute
[Route("api/[controller]")]
If so how resolve this conflict by specifying namespace or some constraints while rendering views in the routes.
I am a beginner. Correct me if I am wrong.
On MVC 6 you can have RESTful APIs as long as Views in the same project and even on a same controller.
One ways to set up routing for you application is to create a map on Startup.cs like this, with IApplicationBuilder:
Then, you can specify the routes for each action:
By setting a [HttpGet] (or any other HTTP verb) on the Action without parameters, it will create a route by convention, following you action's name. That way, you can solve many conflicts. It's also possible to put multiple actions of a same HTTP verb on one Controller.
And as stated above, please ask only one question per post.

Problems (retroactively) adding Web API to asp.net MVC project

I'm taking my first steps with asp.net mvc in Visual Studio 2013 and I've run into a weird problem.
I started my Project as MVC and did NOT check the "Web API" box to include the core references. However now I want to use the Web API functionality. I created a new "somethingController" controller, selected API controller (empty) and Visual Studio did it's magic, creating a routing file, etc.
However when trying to access the URL /api/something/ I geta 404. I believe the routing doesn't work or there is some other problem I haven'T thought about yet...
It works just fine if I create a new Project and checkt the "Web API" box. But if you have a larger project and want to add Web API functionality there must be an easy way to reliable add it to the project, right?
Could anybody please explain
a) Where the problem lies (routing? Missing references? something else?)
and
b) How can one reliably add the Web API stuff to a project that wasn't started with the checkbox checked.
Thank you very much.
Ok, seems I got it working. When you add your first API controller to a project that does not have the Web API checked, a readme file pops up with some additional information:
I tried adding
WebApiConfig.Register(GlobalConfiguration.Configuration);
to the global.asax and it did not work. the readme show the following code
GlobalConfiguration.Configure(WebApiConfig.Register);
that DOES work, although it seems (to me) that both lines do exactly the same thing??
Have you added WebApi.Config file
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
add this in your global.asax
WebApiConfig.Register(GlobalConfiguration.Configuration);

Setting up Web API within WCF Project

I have a little bit of a "strange practise" question. The requirement on an architecture of our project is to setup Web API with (if possible) all MVC goodness within WCF project. That means that WCF and Web API web services would be stood up along each other within one project.
Is this even doable? I've given it a short go and found that even merging the web configs of two projects is very hard.
Thank you for your suggestions and comments,
Jakub
I followed these steps and it worked fine:
Make sure your WCF service is working correctly.
Install WebAPI to your project through Nuget Package Manager
Install-Package Microsoft.AspNet.WebApi
Create Controller folder and write your controller class and methods.
Create global.asax file
Register routes for your services in Application_Start method.
protected void Application_Start(object sender, EventArgs e)
{
RegisterRoutes(RouteTable.Routes);
}
private void RegisterRoutes(RouteCollection routes)
{
routes.MapHttpRoute(
"webapi_route",
"/{controller}/{action}/{id}",
new { controller = "controller_name", action = "method_name", id = RouteParameter.Optional }
);
RouteTable.Routes.Add(new ServiceRoute("", new WebServiceHostFactory(), typeof(service_name)));
}
In fact there are no major restrictions on the use of the two technologies within the same project. By default wcf has a different "pipe line" than asp.net, but until this can be changed. Using the configuration below in web.config it is possible to configure wcf to use the same asp.net pipe line thus sharing the whole life cycle of the objects of the request. But do not believe that this approach is usual for all cases, other factors need to be considered to make that decision, for example, how do you plan to distribute your application? When you release a version of wcf you will also be releasing the web.api, in many cases you may not want this result.
<serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" />
It is possible but with losing the MVC goodness (that means that you will not be able to use for example the built in automatic online documentation for your web services).
Just install Web API through NuGet and then register your route in global.asax. Create your api controller and it should be all good.
EDIT 01.02.2017:
This is no longer true. Since Microsoft approach was to merge MVC and Web API controller. Now anything is possible.

Getting ASP.NET Mvc and Web Forms to work together

Sorry if this as already been asked.
I am currently working on a small feature and am trying to implement the ASP.NET Mvc framework into my current Web Forms web application. I have been following the Professional ASP.NET 3.5 Mvc Chapter 13 pdf document that I recently found on stackoverflow to get Web Forms and Mvc to work together. I have completed all three steps:
Added the references to the libraries System.Web.Mvc, System.Web.Routing, and System.Web.Abstractions
Added the two directories to my web application: controllers and views
Updated the web.config to load the three assemblies mentioned in step one and registered the UrlRoutingModule HttpModule. I also added the initial routing settings to my Global.asax file
RouteTable.Routes.MapRoute(
"Default", "{controller}/{action}/{id}", new { controller = "Support", action = "Index", id = "" }
);
Once I try and run my newly created page following the ASP.NET Mvc framework I get a NullReferenceException on the following piece of code:
<%= Html.Encode(ViewData["Message"]) %>
In my controller I have ViewData["Message"] being set to "Message!" just as a test. Have I missed something setting my web application to work with ASP.NET Mvc?
Any help would be greatly appreciated.
Thanks,
From playing with the early betas, until today, I find it easier to create a new MVC application and "import" my exsiting files into the solution than it is to get all of the settings right in an existing application. I see no reason to get hot and heavy over setting up plumbing I can have written for me from a template. Perhaps I am just too lazy.
I find that I can get "legacy ASP.NET" web forms working fine with MVC. The only dink to the whole project is getting the app routed to my default.aspx to begin with. Much easier than running through multiple steps to include MVC.
I know this is not a direct answer to your question, but I think trying it will solve your problem, as well. Another benefit is you leave the old "legacy" source in case a bug fix comes in. But, then, you should be under source control anyway.

Can ASP.Net MVC Views (*.aspx) be reused in multiple ASP.net MVC projects?

I would like to reuse *.aspx files in multiple ASP.Net MVC projects. Is this possible?
EDIT: Anthony's suggestion of using version control system to share common files across multiple projects solves my question in a practical way. Luckily, since I'm using Subversion, the solution fits me. However, if I wasn't using one, how can this problem still be solved?
Is it possible to do something like this?
Build a redistributable User Control using VS's website precompilation feature. (As described here.)
Reference the output assemblies in the required projects.
Create a modified View engine that instantiates User Controls via generic type parameter.
We then construct controller actions like this:
public ActionResult Shared()
{
return View<SharedPageOrUserControl>();
}
Does that look possible?
One idea you could try would be to:
Create a project (class library) for your shared Views
Add and set any *.aspx markup pages to Embedded Resources in the Properties pane
Add a class "EmbeddedViewResult" that inherits from ActionResult - this would contain logic to ensure the embedded .aspx files are extracted and available on disk when called at the end of a controller action.
So in the projects that you wanted to use the shared Views, the controller actions could return something like
public ActionResult Shared()
{
return new EmbeddedViewResult("SharedLib.SharedPage");
}
I've done something similar with WebForms pages, so it should be possible.
I normally solve this sort of issue via source code control. Most systems (even VSS) allow you to share a file across multiple projects.

Resources