Can you use the attribute-based routing of WebApi 2 with WebForms? - asp.net

As the title states, I'm wondering if you can use the attribute-based routing of WebAPI 2 with WebForms. I feel like this can obviously be done given you can use WebAPI2 just fine in a WebForms application... I just can't figure out how to enable attribute-based routing.
Based on this article, I understand you normally enable it via a call to MapHttpAttributeRoutes() prior to setting up your convention-based routes. But I'm guessing this is the MVC way - I need to know the equivalent for WebForms.
I currently use MapHttpRoute() to set up my convention-based routes, and I'd like to try out the attribute-based routing in WebAPI2. I have updated my project with WebAPI2 - I just need to know how to enable the attribute-based routing feature.
Any info would be appreciated.

You need not do anything special in case of WebForms. Web API attribute routing should work just as in MVC.
If you are using VS 2013, you can test this easily by create a project using "Web Forms" template and then choose "Web API" check box and you should see all the following code generated by this.
WebApiConfig.cs
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// Web API configuration and services
// Web API routes
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
}
Global.asax
public class Global : HttpApplication
{
void Application_Start(object sender, EventArgs e)
{
// Code that runs on application startup
GlobalConfiguration.Configure(WebApiConfig.Register);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
}
}
WebForm's RouteConfig
public static class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
var settings = new FriendlyUrlSettings();
settings.AutoRedirectMode = RedirectMode.Permanent;
routes.EnableFriendlyUrls(settings);
}
}

Related

Asp.Net MVC with Web Api

I am looking for a good approach for implementing intranet Web Application using Web Api(2) with Asp.net MVC(5).
Application is designed in such a way that we use AngularJS SPA at client side and in server side MVC with Web Api as a single application/web site. MVC is because we have to restrict the operations based on the security permissions. We don't render the action buttons(eg. Save, Delete etc) when we call MVC controller for views if the user does not have permission. Other operations are utilizing Web API methods to Save, Delete etc,
Basic idea is
MVC Controllers are for generating views with action buttons removed if the user doesn't have permission(html templates for AngularJS).
Data Manipulation is through Web API(AngularJS $http service web api calls)
Questions here
How do we derive an authentication mechanism which we can utilize for both MVC and Web API?
(We can create Authentication filters but we have to create separate filters for MVC and Web API, right?)
Once the user is authenticated how do we share this info with both MVC Controller and Web Api controller instead of validating the user each request from angular js?
Is it possible to use ASP.Net forms authentication for both MVC and WebApi for authentication?. If so how do we do that?. Will forms authetication token validates for both MVC controller and Web Api controllers automatically using [authorize] attribute?
Also I would like to know, is it a good approach mixing MVC with WebApi with in a single application?
Its a feasible option but not a recommended option.
Since WebApi operation will be inheriting from ApiController
and MVC controller action will be inheriting from Controller Class.
If you want to define route for api and mvc controller then you need to register the route like this in Global.ascx in
Application start
GlobalConfiguration.Configure(WebApiConfig.Register);
RouteConfig.RegisterRoutes(RouteTable.Routes);
RouteConfig Class
public static class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
.....
....
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
}
WebApiConfig Class
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// TODO: Add any additional configuration code.
// Web API routes
config.MapHttpAttributeRoutes();
config.Formatters.XmlFormatter.UseXmlSerializer = true;
config.MessageHandlers.Add(new YourMessageHandlers());
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{action}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
}

Routing in a hybrid app that is classic ASP.Net web forms and MVC

i have inherited an application that is both clasic asp.net web forms and mvc (started as web forms project). I would like to setup routing like MVC. What is the best way to go here? All i need is a push in the right direction.
I know how to setup routing for the MVC only project via global.asa > App_Start > Route Config and area registration cs files.
Environment:
VS 2012, IIS 7, ASP.NET 4.0, classic asp.net web forms and MVC 4.
My thinking:
I am thinking about doing some thing like following, do you guys see an issue here? I may end up with some web.config issues but at this this time i am not sure what those would be. I need your advice to properly setup the structure here.
Global file addition:
protected void Application_Start()
{
RouteConfig.RegisterRoutes(RouteTable.Routes);
}
App_Start > RouteConfig.cs
namespace My.Site
{
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional },
namespaces: new string[] { "My.Site.Controllers" }
);
OTHER ROUTES WILL GO HERE, THESE MAY REDIRECT TO a webform page or to a controller action.
}
}
}
Going through the following to setup all properly.
http://www.hanselman.com/blog/PlugInHybridsASPNETWebFormsAndASPMVCAndASPNETDynamicDataSideBySide.aspx
http://www.hanselman.com/blog/IntegratingASPNETMVC3IntoExistingUpgradedASPNET4WebFormsApplications.aspx
http://www.packtpub.com/article/mixing-aspnet-webforms-and-aspnet-mvc
http://msdn.microsoft.com/en-us/library/dd329551.ASPX

asp.net WEB API: Routing - Action before Controller. Possible workaround?

I am developping a WEB API using asp.net and my goal is to be able to call this type of url's:
/html/countries/...
/json/countries/...
Countries is a controller, and depending on the parameter before it returns different result.
What i did and it doesn't seems to work:
routes.MapRoute(
name: "Default",
url: "api/{action}/{controller}",
defaults: new
{
}
);
CountriesController:
[ActionName("html")]
public string get()
{
//...
}
[ActionName("json")]
public void getType()
{
//...
}
Any sugestions?
EDIT:
I have like 7 controllers.
And there are some possible urls:
/html/{controller}/x/y
/json/{controller}/x/y/order/h
/html/{controller}/x/z/order/y/j
/json/{controller}/x/z/order/y/j
Allow me by start saying that if "html" or json action means "format" those should not be part of your controller they are media types and needs to be configured differently
Web Api v1 defines resources globally in the global.asax on application_start event. Assuming you are using Visual Studio 2013 and based Microsoft default template your method may look like this:
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
GlobalConfiguration.Configure(WebApiConfig.Register);
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
}
WebApi routing configuration occurs here WebApiConfig.Register while your MVC configuration occurs here RouteConfig.RegisterRoutes
Your WebApi routing configuration should look like this
public static class WebApiConfig{
public static void Register(HttpConfiguration config){
config.Routes.MapHttpRoute(
name: "htmltApi",
routeTemplate: "html/{action}/{controller}",
);
config.Routes.MapHttpRoute(
name: "jsonApi",
routeTemplate: "json/{action}/{controller}",
);
...
Another important detail is that WebApi v2 introduced something called Route Attributes those can be used along with your Controller class and can facilitate the routing configuration.
For example:
public class BookController : ApiController{
//where author is a letter(a-Z) with a minimum of 5 character and 10 max.
[Route("html/{id}/{newAuthor:alpha:length(5,10)}")]
public Book Get(int id, string newAuthor){
return new Book() { Title = "SQL Server 2012 id= " + id, Author = "Adrian & " + newAuthor };
}
[Route("json/{id}/{newAuthor:alpha:length(5,10)}/{title}")]
public Book Get(int id, string newAuthor, string title){
return new Book() { Title = "SQL Server 2012 id= " + id, Author = "Adrian & " + newAuthor };
}
...
Thanks to the Dalorzo answer i did find the problem:
The problem occurred because my application was created the following way:
which resulted in creation of both files, RouteConfig.cs (MVC) and WebApiConfig.cs (WEB API):
What is WRONG is that the code in the question is from RouteConfig.cs
After putting the code
config.Routes.MapHttpRoute(
name: "Default",
routeTemplate: "api/{action}/{controller}",
defaults: new
{
action = "html"
}
);
in WebApiConfig.cs, it worked proper way.

Pluralsight 404 not found error

I have a question about MVC3 in the Pluralsight examples. I'm new to MVC and I have what will appear to be a simple question. I downloaded the sample code and added the Routemap to global.asax.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
namespace OdeToFood
{
// Note: For instructions on enabling IIS6 or IIS7 classic mode,
// visit http://go.microsoft.com/?LinkId=9394801
public class MvcApplication : System.Web.HttpApplication
{
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new HandleErrorAttribute());
}
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
"Cuisine",
"cuisine/{name}",
new { controller = "cuisine", action = "Search" }
);
/* routes.MapRoute(
"Cuisine",
"{controller}/{name}",
new { controller = "cuisine", action = "Search" }
); */
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
);
}
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
RegisterGlobalFilters(GlobalFilters.Filters);
RegisterRoutes(RouteTable.Routes);
}
}
}
And added the Controller:
namespace OdeToFood.Controllers
{
public class CuisineController : Controller
{
//
// GET: /Cuisine/
public ActionResult Search()
{
return Content("You have reached the Cuisine controller");
}
}
}
As shown in the tutorial "Controller Action Parameter!" and run the application with the word cuisine (all spelled correctly - even changing to all capitalization as a test) and I still get the HTTP 404 "not found error".
I'm running on Windows 7 with VS 2012 and .net 4.5 installed (this is a new box and may not have ever had previous versions. MVC 3 and MVC 4 are in the new project selection so those must be isntalled correclty.
Any ideas on what I'm doing wrong? Did I miss a step? I see that IIS6 or IIS7 might/must be on the machine? I have come to believe that IIS doesn't run on windows 7. Is that true? Do I require iis? The sample code works fine until this change...
I'm a little over my head here as I learn this new stuff. Thank you for your patience and help!
Try using:
routes.MapRoute(
"Cuisine",
"cuisine/{name}",
new { controller = "cuisine", action = "Search", name = "" }
);
Try using the a MVC Route Debugger so that you can visually see which routes are being matched. The one I use is Phil Haack's, but there are others available:
Install-Package RouteDebugger
Separately, don't you need a name parameter on your search action to match this route?

URL Rewriting in Asp.net MVC 3

I am new to Asp.net MVC.
I am creating web application, where i have to rewrite url with product name.
I am not sure if that is possible or not in MVC.
Like,
http://sitename.com/category1/product1
http://sitename.com/category1/product2
will have same page.
There are facilities to generate friendly urls within MVC.
Check out the article at - http://www.asp.net/mvc/tutorials/older-versions/controllers-and-routing/asp-net-mvc-routing-overview-cs - for an overview of how this is handled in MVC.
Essentially, you need to configure the routes on application startup as follows. This can usually be done in the global.asax file but cna be split for areas etc.
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = "" } // Parameter defaults
);
}
protected void Application_Start()
{
RegisterRoutes(RouteTable.Routes); // Reigster the routes
}
This is the default route but you can define as required.

Resources