Search code examples
c#asp.net-web-apiasp.net-web-api-routing

Web API 2 not working (404)


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.


Solution

  • 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")]