i have been trying for a long time get Web API 2 working. I have read a lot of articles and posts over internet, but so far i have been unlucky.
I just need to get working simple Web API method, but for some reason i am still getting 404 method not found. I really dont know now, where problem can be as it seems to me everything is ok.
I have tried a lot of variations of attributes, configs and so on. I have end up with this code:
Global.asax
AreaRegistration.RegisterAllAreas();
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
GlobalConfiguration.Configure(WebApiConfig.Register);
WebApiConfig.cs
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
var appXmlType = config.Formatters.XmlFormatter.SupportedMediaTypes.FirstOrDefault(x => x.MediaType == "application/xml");
config.Formatters.XmlFormatter.SupportedMediaTypes.Remove(appXmlType);
ApiController
public class ContactFormController : ApiController
{
[Route("~/api/sendemail")]
[HttpPost()]
public IHttpActionResult SendEmail(ContactFormModel contactForm)
{
return Ok();
}
}
Model:
public class ContactFormModel
{
public string Name { get; set; }
public string Email { get; set; }
public string Subject { get; set; }
public string Message { get; set; }
}
jQuery Code
var jsonData = { "Name": name.val(), "Email": email.val(), "Subject": subject.val(), "Message": comment.val() };
$.ajax({
url: "api/sendemail",
type: "POST",
data: jsonData,
cache: false,
...
});
As you can see, it is MVC 5 + Web API 2.
Thanks for help. So simple thing and nothing is working.
please update your global.asax like here:
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
GlobalConfiguration.Configure(WebApiConfig.Register);
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
}
and change [Route("~/api/sendemail")]
to [Route("/api/sendemail")]
For me routing attributes were not working with WebAPI because I had the URL Rewrite module installed in my web.config. Somehow the global routing templates were working with that in place but not the routing attributes above each web method. I removed the <rewrite>
section from within the <system.webServer>
section in web.config and the routing attributes started working.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With