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

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);

Related

MVC 5 in VS2012

I have installed ASP.NET and Web Tools 2013.1 for Visual Studio 2012 which has the MVC 5 templates for Visual Studio 2012. In Project Templates I am able to find the "ASP.NET MVC5 Empty Project" however after creating the Project, if I try to open the same project in the Internet Explorer by Pressing Ctrl+F5 it gives an error saying,
Server Error in '/' Application.
But When I create a MVC 4 Web Application and try to run it the Application works fine and shows the default page of the MVC 4 App.
Is there any other configuration needed to be done on the Visual Studio 2012 to make it run?
An Empty application is just that. Empty. There is no default page. It's an empty project that you have to create the content for.
Microsoft did not supply a default application template for MVC5 in VS2012. VS2013 does have a default template though.
Since it is an empty template it doesn't have a landing page and hence it was throwing the error
Server Error in '/' Application.
if you append the Controller name and view name just like below
localhost:port/[Controller]/[View]
It will show the contents of view.
you can try either edit your routing.config file, or change your url. Usually it will default to index.
This is an example of a route you can maybe add in as a class, if you do not have one already. This controller just means that it defaults to the Home controller, at the action called index.
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
I hope this somewhat helps .

Call controllers from one project to another project

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.

.NET Web Api - 404 - File or directory not found

In short words, everything works on local machine but doesn't when deployed to server "A".
I'm sure someting is missing in server "A", but I don't know what it is, and I don't have access there to make changes or proper testing.
So I'm here to aks for help and ideas of what the problem may be so that I can advise the person in charge of server "A", or whatever changes I need to make on my project to make it work there.
That being said, lets talk about my project...
I'm using Web Api, and a route is defined in the global.asax as such:
RouteTable.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = System.Web.Http.RouteParameter.Optional });
I'm calling the controllers using Jquery ajax and Kendo UI, as such:
(this is a fake example just to prove the point)
read: {
url: function () {
return "../api/Member/123";
}
}
Again, everything works great on local server, but when I deploy it, I get for every web api call:
404 - File or directory not found.
Nothing else.
Things to consider:
I'm compiling the project with .NET 4.0 framework.
The website on server "A" is set up to use .NET 4.0 classic (could this be a problem?)
I don't think MVC 4 is installed in server "A". Does Web Api requires MVC?
Server "A" is running IIS 7
I added the following to the web.config file, but still get the 404 error:
<modules runAllManagedModulesForAllRequests="true"/>
Let me know if you need any other information.
Thanks for your help!!
Download MVC4 to use ASP.NET WebAPI. http://www.microsoft.com/en-us/download/details.aspx?id=30683

mixed MVC routing for MVC app under web forms app

I have an instance of BlogEngine.net installed at the root of my hosted server. I wanted to play with ASP.Net MVC to write a small app and installed that app under a folder off the root.
I am able to see the http://example.com/testApp/ but the the routed pages like http://example.com/testApp/edit are giving 404's.
I have searched around and I'm just not clear what is needed to get the routing right. Do I need to set something in BlogEngine's web.config or do I need to be doing something in my applications settings?
The host is WinHost.com and it is IIS7
Edit/Update
So I understand that the http://example.com/testApp gets served because there is a default.aspx under that directory and that the routed pages don't get served because they don't have physical aspx's. The /edit gets routed to the edit view just fine when I launch it under Visual Studio.
I am guessing that the BlogEngine.net's global.asax is trying to map these pages to the BlogEngine world and not routing them to my testApp.
If that is the case then my question is how do I get BlogEngine to forward the requests to my testApp? I was hoping that I was missing something simple in the web.config because if I have to add stuff to BlogEngine's global.asax to do routing then won't I need to rebuild BlogEngine?
Based on the information I found in the MVC tutorial, I have discovered why my routing wasn't working.
My request processing mode on the hosted server was configured to use the Classic .NET AppPool not Integrated mode. To get it to work in classic mode you need to either modify the route table to use file extensions or create a wild card script map.
I was able to keep BlogEngine working using integrated mode so all that I needed to resolve this issue was to change the mode.
Hope this helps someone...
Do you have a Edit.aspx file existing in your application for your testApp controller? The way the default route works is:
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = "" } // Parameter defaults
);
So by default, when you access Home/Index, ASP.NET MVC looks for Index.aspx
In your case, your routing consists of (I just made this up):
routes.MapRoute(
"CustomRoute", // Route name
"{controller}/{action}/{id}", // URL with parameters, id is optional.
new { controller = "testApp", action = "Edit", id = "" } // Parameter defaults
);
Where you are trying to use Edit.aspx
Inside of your Global.asax file is where all your custom routing exists, have you touched that file at all or no? The rule of thumb that I have heard about is that you want to write all the custom routing first prior to the default.
EDIT:
I also stumbled across this, might be helpful
There are four sections in the configuration file that are relevant to routing: the system.web.httpModules section, the system.web.httpHandlers section, the system.webserver.modules section, and the system.webserver.handlers section. Be careful not to delete these sections because without these sections routing will no longer work.
Taking from here
Good luck, hope this helps.

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.

Resources