how to fix this error WebApiConfig in Global.asax? - c#

There's a great thread running here:
How to add Web API to an existing ASP.NET MVC (5) Web Application project?
Unfortunately, for me is having an error on WebApiConfig in Global.asax, so how can i fix this error i even installed nugets.
The name 'WebApiConfig' does not exist in the current context
Global.asax
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
GlobalConfiguration.Configure(WebApiConfig.Register);
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
}
WebApiConfig
public class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// Web API routes
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
// WebAPI when dealing with JSON & JavaScript!
// Setup json serialization to serialize classes to camel (std. Json format)
var formatter = GlobalConfiguration.Configuration.Formatters.JsonFormatter;
formatter.SerializerSettings.ContractResolver =
new Newtonsoft.Json.Serialization.CamelCasePropertyNamesContractResolver();
}
}

As you copied code from other project , you are merging web api in existing mvc project so many time two project have different namespace so you have to add namespace or change namespace of webapiconfig.

Related

How to properly connect JSON configuration file to project without using .NETCore

I have a Web API project which I have a custom JSON config file that I would like to incorporate into my project without using Microsoft.Extensions.Configuration. I am fairly new to this but I would like to avoid using any .Net Core methods or routes.
Below are snippets are the files involved:
Web.Config
<appSettings configSource="Config\base\appsettings.json"></appSettings>
appsettings.json
{
"siteURL": "https://helloworld.com",
"TokenSecretKey": "justanothersecret",
"URI.Key": "anotherkey",
"ClientTokenSharedSecret": "somevalue",
"TwoFactorSessionExpirationInMinutes": "43200",
"Email.From": "noreply#thatonesite.com",
"Email.Server": "192.168.1.1",
"Email.Server.User": "user",
"Email.Server.Password": "pword",
}
WebApiConfig.cs
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// Web API configuration and services
var cors = new EnableCorsAttribute("*", "*", "*");
config.EnableCors(cors);
// Web API routes
config.MapHttpAttributeRoutes();
GlobalConfiguration.Configuration.Formatters.Add(new FormMultipartEncodedMediaTypeFormatter());
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
}
Global.asax.cs
public class WebApiApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
GlobalConfiguration.Configure(WebApiConfig.Register);
}
}
My aim is to have these settings incorporated in the project and be able to use where ever in the project.

Unable to hit any attributed routes in new WebApi project - only 404s returned

I'm building a new Web API project from scratch and am unable to get any response other than 404 (Not Found).
The routes for each controller and method are declared in attributes.
Here is my Global.asax Application_Start method.
protected void Application_Start()
{
log4net.Config.XmlConfigurator.Configure();
Log.Info("Application_Start...");
GlobalConfiguration.Configure(IoCConfig.Register);
Collaboral.Common.DB.DatabaseUtil.SetRetryStratPol();
GlobalConfiguration.Configuration.EnsureInitialized();
}
That code calls the method IoCConfig.Register.
public static void Register(HttpConfiguration config)
{
config.DependencyResolver = new TinyIocWebApiDependencyResolver(RegisterDependencies());
config.EnableCors(new EnableCorsAttribute(origins: "*", headers: "*", methods: "*"));
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
foreach (var route in config.Routes)
{
Log.Info($"{nameof(Register)}: Route = \"{route.RouteTemplate}\"");
}
}
As can be seen, I'm logging the routes in the config.Routes collection, and I can see from the log file that this collection contains only the default route which I have manually mapped.
WebApiApplication | - Application_Start...|
IoCConfig | - Register: Route = ""|
IoCConfig | - Register: Route = "api/{controller}/{id}"|
And here is an example of how I've used the routing attributes.
namespace MyApi.Controllers
{
[BasicHttpAuthorize(RequireAuthentication = true)]
[RoutePrefix("v1/projects")]
public class ProjectsController : ApiController
{
[Route("{projectId:guid}/assocs")]
[HttpGet]
[Authorize(Roles = // ...)]
public IHttpActionResult GetAssociations(Guid projectId)
{
// ...
}
The URL I'm attempting is
http://localhost/myapi/v1/projects/bbe89597-28ae-40d5-8071-56dfb222f97b/assocs
Some additional points:
this WebApi project is replacing an older version which has been excluded from the solution. The routes are identical
the project is hosted as an application in IIS. I'm using the same application as the older API but the application's settings (in IIS) point to the local folder for the newer project
What am I missing?
Why you are using 'myapi' in your endpoint? your endpoint should be like
http://localhost/v1/projects/bbe89597-28ae-40d5-8071-56dfb222f97b/assocs
You can refer this link for more information.
https://learn.microsoft.com/en-us/aspnet/web-api/overview/web-api-routing-and-actions/attribute-routing-in-web-api-2

ASP MVC 4 + Web API

I have ASP MVC 4 project and the Web API.
I wanna use Web API from the main application. i did this:
WebAPI Project
WebApiConfig.cs
public static void Register(HttpConfiguration config) {
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
config.Formatters.JsonFormatter.SupportedMediaTypes
.Add(new MediaTypeHeaderValue("text/html"));
}
Global.asax
protected void Application_Start() {
GlobalConfiguration.Configure(WebApiConfig.Register);
}
StatisticsController.cs
public class StatisticsController : ApiController {
TopUserFactory topUserFactory = new TopUserFactory();
// GET api/statistics/topUsers
[ActionName("topUsers")]
public List<TopUser> Get() {
return topUserFactory.Top10Users();
}
}
But nothing happens when i go for localhost:31003/api/statistics/{topUsers}
How to use WebAPI project from other project?
When working with multiple sites locally they will have different port numbers.
You can check the port numbers by clicking the IIS Express icon on your taskbar:
You can change the port number by adding a configuration:
Changing project port number in Visual Studio 2013
your code looks ok. it's very easy to get the routes wrong with WebAPI, ensure you're doing a parameter-less GET to http://localhost:31003/api/statistics/topUsers
failing that, use this tool: https://www.nuget.org/packages/routedebugger/

Unable to get multiple literal routings to work in the same controller - Web Api 2

I'm using attribute routing and am having this controller with two Get-methods.
When requesting any of these two Get methods I get 404 back and I don't understand why since I've followed this guide from Microsoft (especially this part).
This is how the Controller looks like:
[RoutePrefix("api/rolesubscriptions")]
public class RoleSubscriptionsController : ApiController
{
Route("roles")]
public async Task<IHttpActionResult> GetRoles()
{
}
[Route("tags")]
public async Task<IHttpActionResult> GetTags()
{
}
}
And this is my WebApiConfig.cs file
public static void Register(HttpConfiguration config)
{
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
Now based on this configuration I think that I would be able to do these requests
/api/rolesubscriptions/roles
and
/api/rolesubscriptions/tags
But both these requests return 404. Any help to help solve my problem is very appreciated.
EDIT 1
This is how my Application_Start() looks like
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
GlobalConfiguration.Configure(WebApiConfig.Register);
}
The Startup class exists but doesn't have any code that has to do with routing, only authentication.
public void Configuration(IAppBuilder app)
{
app.UseCors(CorsOptions.AllowAll);
// Authenication code omitted
}

Attribute routing not working MVC5

This is a long post. I am using attribute routing as described here:
http://blogs.msdn.com/b/webdev/archive/2013/10/17/attribute-routing-in-asp-net-mvc-5.aspx#enabling-attribute-routing
I have placed in WebApiConfig.cs:
public static void Register(HttpConfiguration config)
{
config.EnableCors();
+ config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
}
in Global.asax.cs
AreaRegistration.RegisterAllAreas();
+ //WebApiConfig.Register(GlobalConfiguration.Configuration);
+ GlobalConfiguration.Configure(WebApiConfig.Register);
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
and I am using a webapi controller with:
public class HelloController : ApiController
{
[Route("Services/test/Application/{id}")]
public string GetTest(int id)
{
return "1";
}
}
I am using Postman Chrome extension to test. On my own computer when I test in Visual Studio this is working perfectly: http://localhost:6296/Services/test/Application/12
and returns the expected result, but after I deploy it on a site, it does not work: http://www.mytest.com/Services/test/Application/12 (tested even on the server localhost: http://localhost/Services/test/Application/12)
and returns:
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: /Services/test/Application/12
The reference System.Web.Mvc (version 5.2.3.0) is marked as "copy local = true". No authorization is used. Classic webapi controlls work perfectly on the server and locally.
Question: what could be wrong and where should I start looking?!
Add this to your WebApiConfig.cs
public static void RegisterRoutes(RouteCollection routes)
{
routes.MapMvcAttributeRoutes();
}

Categories

Resources