Adding Web API to MVC 5 project (API takes over) - c#

I've gone over all stack over flow QAs and online tutorials, to add a Web API to my current MVC project.
The Web API works, the MVC works only if I put the routing path into the url.
I want the MVC routing to come up as default, but for some reason it always tries to do the API logic.
I'm hoping its something simple I've missed
What I have done so far.
Web API Config class
Default, not really changed anything
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 }
);
}
}
MVC config class
Default, not really changed anything
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 }
);
}
}
Global Config class
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
GlobalConfiguration.Configure(WebApiConfig.Register);
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
}
API Controller class
Default, not really changed anything
public class RegistrationController : ApiController
{
// GET: api/Registration
public IEnumerable<string> Get()
{
return new string[] { "value1", "value2" };
}
// GET: api/Registration/5
public string Get(int id)
{
return "value";
}
MVC home Controller class
Default, not really changed anything
namespace MVCPortal.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
}}
This is the error I'm getting

Related

Web API Attribute routing in Sitecore 8.1 not working

As Atrribute routing does not work in sitecore 8.1 out of the box, I am following https://github.com/Krusen/Sitecore.WebApi
And got the uget package for Krusen.Sitecore.WebApi.Custom.
This is my ConfigureWebApi class
public class ConfigureWebApi
{
public void Process(PipelineArgs args)
{
GlobalConfiguration.Configure(config => config.Routes.MapHttpRoute(
name: "myApi",
routeTemplate: "api/{controller}/{action}/{id}",
defaults: new { id = RouteParameter.Optional }
));
GlobalConfiguration.Configure(config => config.MapHttpAttributeRoutes());
GlobalConfiguration.Configure(ReplaceControllerSelector);
}
private static void ReplaceControllerSelector(HttpConfiguration config)
{
config.Services.Replace(typeof (IHttpControllerSelector),
new CustomHttpControllerSelector(config, new NamespaceQualifiedUniqueNameGenerator()));
}
}
And this is my controller
[RoutePrefix("windows")]
public class WmsController : ApiController
{
[HttpGet]
[Route("hi")]
public IHttpActionResult Hello()
{
return Ok("Welcome to my Api.");
}
}
When I call this:
http://my.api.local/api/wms/hello
works.
But when I call
http://my.api.local/api/windows/hi
does not work. It says 404.
Am I missing something !!
The second call is not working because Attribute routing must be configured before Convention-based routes to avoid route conflicts.
public void Process(PipelineArgs args) {
GlobalConfiguration.Configure(config => {
// Map Attribute Routes
config.MapHttpAttributeRoutes();
// Map Convention-based Routes
config.Routes.MapHttpRoute(
name: "myApi",
routeTemplate: "api/{controller}/{action}/{id}",
defaults: new { id = RouteParameter.Optional }
);
// Replace IHttpControllerSelector with our custom implementation
ReplaceControllerSelector(config);
});
}
Which I also believe is how it was shown in the documentation in the linked repo
Secondly based on the RoutePrefix("window") and Route("hi") in the ApiController the mapped attribute route would be mapped as
http://my.api.local/windows/hi
To get http://my.api.local/api/windows/hi to map to the desired action you would need to update the route prefix as already explained in one of the other answers.
You need to add "api/" into your controller attribute routing
[RoutePrefix("api/windows")]
public class WmsController : ApiController
{
[HttpGet]
[Route("hi")]
public IHttpActionResult Hello()
{
return Ok("Welcome to my Api.");
}
}

Not differentiating between Action names in url Path - asp.net web api

I am getting really weird routing issues when calling actions in my APIController. I have a WebApp, but needed an APIController so I added that as well as WebAPIConfig.cs to App_start and Global.asax.
However, when I try to call different Actions inside the APIController, it seems to not differentiate between the Actions unless I add a parameter. For example, if I call api/controller/happy it enters the same Action as api/controller/sad. It enters the Action that was created first in the Controller.
It makes no sense to me, the Action-names are not being considered in the URL.
my API Controller:
public class RegistrationManagerController : ApiController
{
EventHelper eh = new EventHelper();
[HttpGet]
public IHttpActionResult IsUserRegistered(string skypeid)
{
var skypeuser = Exist.CheckIfRegistered(skypeid);
return Ok(skypeuser);
}
[HttpGet]
public async Task<IHttpActionResult> Happy()
{
var events = await eh.GetHappyRecent();
return Ok(events);
}
[HttpGet]
public async Task<IHttpActionResult> Sad()
{
var events = await eh.GetSadRecent();
return Ok(events);
}
[HttpPost]
public async Task<IHttpActionResult> UpdateEvent() //TODO id send in body?
{
await eh.Update("id");
return Ok();
}
}
My 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 }
);
}
}
My RouteConfig (This is a webapp, not a web API):
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapMvcAttributeRoutes();// New feature
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
}
Routetemplate should be
routeTemplate: "api/{controller}/{action}/{id}"
WebApi follows REST principals so it doesn't route the same way an MVC Controller routes.
Check out this answer here I think it will help you
need route for my web api 2 controller

I have multiple controllers in web api MVC but Help page is showing only one controller?

In my project i have multiple controllers but when compile it. It shows only some method of one controller. I am stuck in this problem from two days. Can any one help me out. I will be very thankful to you.
It is global.asax file.
public class WebApiApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
GlobalConfiguration.Configure(WebConfig.Register);
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
}
Here is Web config:
public class WebConfig
{
public static void Register(HttpConfiguration config)
{
// Web API routes
// config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "apsi-info",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional });
}
}
This is one of the controller class:
namespace EpubAPI.Controllers
{
[Authorize]
[RoutePrefix("api/Announce")]
public class AnnouncementController : ApiController
{
// GET api/<controller>
[Route("GetData")]
[HttpGet]
public List<EAnnouncement> Get(string code)
{
return AnnouncementC.getdata(code);
}
[Route]
[HttpPost]
public void Post(EAnnouncement announcement)
{
AnnouncementC.insert(announcement);
}
}
You need to verify it is pubilc, it ends with controller and you have routing
routes.MapHttpRoute(
name: "API Default",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
In WebApiConfig.cs

API controller in MVC App not working

I have created an mvc application with SSO. I have added an Api controller, but whenever i try to get data from it, i get error.
URI= https://localhost:44305/api/graph/get
Error:
Server Error in '/' Application.
The resource cannot be found.
Description: HTTP 404. The resource you are looking for (or one of its dependencies) could have been removed, had its name changed, or is temporarily unavailable. Please review the following URL and make sure that it is spelled correctly.
Requested URL: /api/graph/get
Here is my Route config
public class RouteConfig
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
//routes.MapRoute(
// name: "Default",
// url: "{controller}/{action}/{id}",
// defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional });
routes.MapRoute(
name: "Default",
url: "api/{controller}/{action}/{id}",
defaults: new { controller = "Graph", action = "Get", id = UrlParameter.Optional }
);
}
}
This is my web api controller
public JsonResult<List<Claim>> Get()
{
var principal = (User as ClaimsPrincipal);
List<Claim> claimsList = new List<Claim>();
foreach (var claim in principal.Claims)
{
claimsList.Add(claim);
}
return Json<List<Claim>>(claimsList);
}
Not getting any build error. Any help is appreciated
Hy Guys.Thanks for all your help. I have figured out the solution. The answer is that in Global.asax.cs,
GlobalConfiguration.Configure(WebApiConfig.Register)
has to be called before
RouteConfig.RegisterRoutes(RouteTable.Routes).
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}",
defaults: new { controller = "Default", action = "Index", id = UrlParameter.Optional }
);
}
}
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultDataApi",
routeTemplate: "Api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
}
public class MvcApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
GlobalConfiguration.Configure(WebApiConfig.Register);
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
FluentValidationModelValidatorProvider.Configure();
}
}
You should have 2 config files:
RoutesConfig.cs and WebApiConfig.cs
RoutesConfig should look like this:
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
Log.Instance().Debug("Registering Routes");
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapMvcAttributeRoutes();
routes.MapRoute("Default", "{controller}/{action}/{id}", new { controller = "Home", action = "Index", id = UrlParameter.Optional });
}
}
WebApiConfig.cs should look like this:
public static class WebApiConfig
{
public static void Configure(HttpConfiguration config)
{
ConfigureRouting(config);
ConfigureFormatters(config);
}
private static void ConfigureFormatters(HttpConfiguration config)
{
config.Formatters.JsonFormatter.SerializerSettings.Converters.Add(new NiceEnumConverter());
}
private static void ConfigureRouting(HttpConfiguration config)
{
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional, #namespace = "api" });
}
}
Within global.asax.cs you should have something like this:
public class MvcApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
// Register them in this order
GlobalConfiguration.Configure(WebApiConfig.Configure); //registers WebApi routes
RouteConfig.RegisterRoutes(RouteTable.Routes); //register MVC routes
BundleConfig.RegisterBundles(BundleTable.Bundles);
}
}
Your controller does look a little strange why not let the default serialiser take care for things for you:
public IEnumerable<Claim> Get()
{
var principal = (User as ClaimsPrincipal);
List<Claim> claimsList = new List<Claim>();
foreach (var claim in principal.Claims)
{
claimsList.Add(claim);
}
return claimsList;
}
EDIT: removed redundant code
Assuming the name of your controller is GraphController, I think the url you should be using is /api/graph/get.
If it's named something different, you'll need to adjust the url accordingly.
Also, there's a separate .cs file in MVC projects you should use to manage WebAPI routes - WebApiConfig.cs

Use WebApi controller as default instead of MVC vontroller

I have a webapi project and I don't want to return any html or razor views. I want the default controller and action to be an HTTP GET for one of my API controllers. My code is the following:
MVC route config:
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
RouteTable.Routes.MapRoute(
"Default",
"{controller}/{id}",
new { controller = "Enpoint", action = "Get", id = UrlParameter.Optional }
);
}
}
WebApi route config:
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
config.Routes.MapHttpRoute(
name: "ApiDefault",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
}
Application_Start:
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
WebApiConfig.Register(GlobalConfiguration.Configuration);
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
}
Do you know how can I configure the router to redirect to by default:
GET /api/home

Categories

Resources