When creating a web API with .NET standard there are two Route namespaces available.
- System.Web.Mvc.Route()
- System.Web.Http.Route()
First one used when the controller class is extended by your class in which you are defining the attribute route.
e.g.
public class HomeController : Controller
{
[System.Web.Mvc.Route()]
public ActionResult Index()
{
this.HttpContext.Response.AddHeader("status","404");
return Content("Not Found");
}
}
Second one used when the ApiController is extended by your class e.g.
[System.Web.Http.Route("api/getallinfo")]
public class GetAllInfoController : ApiController
{
[System.Web.Http.HttpGet]
public List<DbSchema> Index()
{
return AllDataStore.AllData.ToList();
}
}
The Web API config file will look like below after CORS enabled and XML disabled for response formats:
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// Web API configuration and services
// Web API routes
config.MapHttpAttributeRoutes();
// do not include the forward slash for origin urls
EnableCorsAttribute cors = new EnableCorsAttribute("http://localhost:3000", "*", "*");
config.EnableCors(cors);
config.Formatters.Remove(config.Formatters.XmlFormatter);
}
}
You have to add CORS nuget package in order to CORS to work properly.
Route Config file will look like below after enabling Mvc route attributes:
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapMvcAttributeRoutes();
}
}
Global.asax will look like below:
public class WebApiApplication : 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);
}
}