Adding Web API 2 manually - getting 404 - asp.net-web-api

I've returned to a solution that was put on hold and when I originally created it, I didn't tick Web API. I've added it manually but when I call my URL i'm recieving a 404. I suspect I am missing some configuration but I'm not sure.
My web api controller
[RoutePrefix("search")]
public class SearchController : BaseWebApiController
{
private readonly IAmtProxy _amtProxy;
public SearchController(IAmtProxy amtProxy)
{
this._amtProxy = amtProxy;
}
[HttpGet]
[Route("supportticket/{id}")]
public HttpResponseMessage GetSupportTicket(int id)
{
try
{
var result = _amtProxy.GetSupportTicketById(id);
return GetResponse(result);
}
catch (Exception e)
{
return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, e.Message);
}
}
[HttpGet]
[Route("supportticket")]
public HttpResponseMessage GetAllSupportTickets()
{
try
{
var result = _amtProxy.GetAllSupportTickets();
return GetResponse(result);
}
catch (Exception e)
{
return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, e.Message);
}
}
}
Example of url that returns 404
http://localhost:60541/search/supporticket/1
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: /search/supporticket/1
Application_start in global.asax.cs has this code:
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
GlobalConfiguration.Configure(WebApiConfig.Register);
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
Bootstrapper.Initialise();
}
I also have my WebApiConfig
public static 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});
}
}
Finally with nuget I got web api 2 and it installed successfully.
Does anyone know what I could be missing?

Your config looks fine.
It appears that you have misspelled the url:
http://localhost:60541/search/supporticket/1
It should be:
http://localhost:60541/search/supportticket/1
According to your implementation:
[Route("supportticket/{id}")]

Related

Web API error - Server Error in '/api' Application

After publishing Web API to IIS, which is a child of an AngularJs IIS site, I can reach 'https://localhost/api' and see all endpoints; but when I try to reach some specific endpoint with a GET request, I get an error
Server Error in '/' Application
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);
}
}
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
config.SuppressDefaultHostAuthentication();
config.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType));
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
}
[RoutePrefix("api/branches")]
public class BranchesController : ApiBaseController
{
[HttpGet]
[Route("getBranches")]
public async Task<JsonResult<List<BranchDto>>> GetActiveBranches()
{
var branches = new List<BranchDto>();
var models = await WarehouseUnitOfWork.BranchRepository.GetActiveBranches();
if (models != null && models.Count > 0)
{
branches.AddRange(AutoMapper.Mapper.Map<List<Branch>, List<BranchDto>>(models));
}
return Json(branches, new JsonSerializerSettings
{
ContractResolver = new WarehouseCustomContractResolver()
});
}
}
Any ideas how to solve this?
The solution for my case was to deploy the Frontend into the main IIS site, and inside it create an application called v1 for the Backend.
Then within my angularJS I defined the Production app to make the http requests to /v1/api instead of /api.

Web api call works locally but not on Azure

I have same issue as per following questions and tried answer but never resolve issue
Web api interface works locally but not on Azure
Web API interface works locally but gets 404 after deployed to Azure Website
and many more similar type of...
When i tried to call api it says 404 Not Found
my WebApi.config file
// Web API routes
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "versionApi",
routeTemplate: "api/{version}/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
API Controller
[Authorize]
[RequiresSSL]
[RoutePrefix("api/v2/Configuration")]
public class ConfigurationAPIv2Controller : ApiController
{
[Dependency]
public IConfigurationServicev2 configurationService { get; set; }
[Dependency]
public IAccountService accountService { get; set; }
#region testapi
[Route("getstring")]
[HttpGet]
public IHttpActionResult getstring()
{
return Ok("Success");
}
[Route("putstring")]
[HttpPut]
public IHttpActionResult putstring()
{
return Ok("Success");
}
#endregion
And Folder Structure is like :
i got follwowing issue for both get and Put method
404 error might caused by route issue. Since you are using route attribute for your Web API. Please make sure GlobalConfiguration.Configure(WebApiConfig.Register); is above other code.
protected void Application_Start()
{
GlobalConfiguration.Configure(WebApiConfig.Register);
AreaRegistration.RegisterAllAreas();
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
}
And config.MapHttpAttributeRoutes(); code is above other routes configuration.
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "versionApi",
routeTemplate: "api/{version}/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
In addition, try to delete following code in your Controller to test whether it is related to the dependent injection module.
[Dependency]
public IConfigurationServicev2 configurationService { get; set; }
[Dependency]
public IAccountService accountService { get; set; }
If it also can't work for you. You could get the detail error message from web server after setting IncludeErrorDetailPolicy property in WebApiConfig class.
config.IncludeErrorDetailPolicy = IncludeErrorDetailPolicy.Always;
Visual Studio does not add a default.html page to wwwroot and IIS does.
Just add default.html page to wwwroot in your project, then re-deploy to Azure.

Web Api with Sitecore 8.1

I've been trying to get Web Api to work with Sitecore 8.1.
I installed this package: https://www.nuget.org/packages/Krusen.Sitecore.WebApi.Custom/ and I modified the ConfigureWebApi to the following:
public class ConfigureWebApi
{
public void Process(PipelineArgs args)
{
GlobalConfiguration.Configure(config => config.Routes.MapHttpRoute("API Default", "api/{controller}/{id}",
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()));
}
}
However, whenever I use post requests, I get the following error:
{"Message":"The requested resource does not support http method
'POST'."}. Get requests work.
This is the implementation of the controller:
[RoutePrefix("api/authentication")]
public class AuthenticationController : ApiController
{
[Route("email")]
[HttpPost]
public bool Login([FromBody] string email)
{
return true;
}
}
I figured out what the error was. When my controller was called AuthenticationController it gave the following error:
The requested document was not found
If I called it something else, the web api worked as a charm e.g.
public TestController : ApiController {
//Code goes here
}

web api - message handler attribute routing

Does anyone know whether message handler can work simultaneously with attribute routing in Web API 2.x? I got a custom message handler to work using conventional routing, then after adding attribute routing, it stops working. I am not sure whether it's not supported or if I had misconfigured something. Any help is greatly appreciated.
1) before attribute routing
--- WebApiConfig.cs code snippet (simplified)----
config.Routes.MapHttpRoute(
name:"DefaultApi",
routeTemplate: "api/{controller}",
defaults: null,
constraints: null,
handler: my-message-handler-object
);
--- MyController.cs code snippet (simplified)----
public class MyController : ApiController
{
[HttpGet]
public IHttpActionResult CheckInServices(...)
{
...
}
}
2) after attribute routing
--- WebApiConfig.cs code snippet (simplified)----
public static void Register(HttpConfiguration config)
{
// Web API routes
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name:"DefaultApi",
routeTemplate:"api/vendor",
defaults: new { controller = "Users" },
constraints: null,
handler: my-message-handler-object
);
}
--- MyController.cs code snippet (simplified)----
[RoutePrefix("api/vendor/{vendorID:long}/service")]
public class MyController : ApiController
{
[HttpPost]
[Route("{serviceID:long}")]
public IHttpActionResult CheckInServices(...)
{
...
}
}
Thanks,
Cody
Global message handlers will work - just set it up on start up.
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
config.MessageHandlers.Add(new YourAuthenticationHandler());
}
}
I'm unsure if per route Message Handlers work with Attribute Routing.

Web API - supported verbs?

I am putting together a talk for a local Code Camp and am trying to understand the nuances of HTTP Verbs in ApiController. Several things about ApiController significantly changed between Beta, RC and final release, and the advice on how you can set this up is conflicting and sometimes wrong.
Assuming I am just leaving the standard routing in WebApiConfig:
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
(since you can really put things on their head if you add in an {action} parameter here)
I understand how the convention is working for simple Crud calls like:
// GET api/values
public IEnumerable<string> Get()
{
return new string[] { "value1", "value2" };
}
// GET api/values/5
public string Get(int id)
{
return "value";
}
// POST api/values
public void Post([FromBody]string value)
{
}
Or that you can change these as long as they start with the verb name:
// GET api/values/5
public string GetMyStuff(int id)
{
return "value";
}
However, the initial spec says that ApiController supports Get, Put, Post and Delete.
Yet I can add methods for:
public void HeadOfTheClass()
{
}
Which works for a Head verb, but I can’t add methods for the obscure or non-existent verbs:
public void MKCOL()
{
}
public void Bubba()
{
}
What is the full list of Native “Supported” verbs?
I can however add support for these methods by using the AcceptVerb attribute:
[AcceptVerbs("MKCOL")]
public void MKCOL()
{
}
[AcceptVerbs("Bubba")]
public void Bubba()
{
}
This also works, or for any “defined” verb use the Http attributes:
[HttpHead]
public void HeadOfTheClass()
{
}
[HttpGet]
public void Bubba()
{
}
Which is correct or preferred? (There was also attributes like [GET] and [POST] as well, are these deprecated?)
Are [HttpBindNever] and [NonAction] equivalent?
I love open source. :)
From ReflectedHttpActionDescriptor:
private static readonly HttpMethod[] _supportedHttpMethodsByConvention =
{
HttpMethod.Get,
HttpMethod.Post,
HttpMethod.Put,
HttpMethod.Delete,
HttpMethod.Head,
HttpMethod.Options,
new HttpMethod("PATCH")
};

Resources