Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 505
Daniel Avatar asked Jul 25 '14 10:07

Daniel


Video Answer


2 Answers

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

like image 50
sylwester Avatar answered Oct 09 '22 05:10

sylwester


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.

like image 29
DougK Avatar answered Oct 09 '22 04:10

DougK