I wrote a web api with mvc .net, but I am getting a 404 error

Viewed 134

my script is bellow

$(function () {
        $(".formSubmit").click(function () {
            var cName = $('#cName').val();
            var cSurname = $('#cSurname').val();
            var cEmail = $('#cEmail').val();
            var cMessage = $('#cMessage').val();
            console.log(cMessage);
            console.log(cEmail);
            console.log(cSurname);
            console.log(cName);
            if (cName != null && cName != '' && cSurname != null && cSurname != '' && cEmail != null && cEmail != '' && cMessage != null && cMessage != '') {
                $.ajax({
                    type: "GET",
                    url: "/api/contactusapi/" + cName + "/" + cSurname + "/" + cEmail + "/" + cMessage + "/?",
                    contentType: "json",
                    dataType: "json",
                    success: function (data) {
                        if (data != null) {

                        }
                    },
                    error: function (xhr) {
                        alert(xhr.responseText);
                    }
                });
            }
        });
    });

And my "contactusapi" api is below

namespace iskorumacom.Controllers
{
    public class ContactUsApiController : ApiController
    {
        [HttpGet]
        public int Get(string cName, string cSurname, string cEmail, string cMessage)
        {
            try
            {
                using (Data.DataClassesDataContext dc = new Data.DataClassesDataContext())
                {
                string cHTML =
                              "<h3></h3>" +
                              "<b>Ad:</b> " + cName + "<br />" +
                              "<b>Soyad :</b> " + cSurname + "<br />" +
                              "<b>e-Mail :</b> " + cEmail + "<br />" +
                              "<b>Mesaj :</b> " + cMessage;

                using (MailMessage MailMessageLocal = new MailMessage())
                {
                    MailMessageLocal.From =
                        new MailAddress("m@majorworx.com", cName + " " + cSurname, System.Text.Encoding.UTF8);


                    MailMessageLocal.To.Add("m@majorworx.com");

                    MailMessageLocal.Subject = "İletişim Formu Formu";
                    MailMessageLocal.IsBodyHtml = true;
                    MailMessageLocal.BodyEncoding = System.Text.Encoding.UTF8;
                    MailMessageLocal.Body = cHTML;
                    MailMessageLocal.Priority = MailPriority.High;

                    using (SmtpClient SmtpClientLocal = new SmtpClient())
                    {
                       
                        return -1;

                    }
                }


            }
        }
        catch
        {
            return 0;
        }
    }
  }
}

and my route.config folder

public static void RegisterRoutes(RouteCollection routes)
{
     routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

        routes.MapRoute(
            name: "Default",
            url: "{controller}/{action}/{id}",
            defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional },
            namespaces: new string[] { "iskorumacom.Controllers" }
        );
    }
4 Answers

You are controller is inheriting from ApiController, but your route are configured for a MVC controller.

  1. If you want to use ApiController then configure route using .MapHttpRoute method.
  2. If you want to configure using .MapRoute method then inherit you controller from Controller instead of ApiController.

Also, in your url you are adding /api after your host and port. The /api is defined in routeTemplate when defining your route using .MapHttpRoute as below -

 config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );

In your case configure your WebApiConfig as -

  config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );

And now call your api using url /api/contactusapi?cName=myname&cSurname=mysurname&cEmail=myemail&cMessage=mymessage

Or alternatively you can add Route attribute to your action method as below -

namespace iskorumacom.Controllers
{
   public class ContactUsApiController : ApiController
   {
      [HttpGet]          
      [Route("api/contactus/{cName}/{cSurName}/{cEmail}/{cMessage}")]
      public int Get(string cName, string cSurname, string cEmail, string cMessage) {
         // Your code
      }
   }
}

And now call your API as - /api/contactus/myname/mysurname/myemail/mymessage

WEBAPİ.CONFİG:

public static void Register(HttpConfiguration config)
        {
            config.MapHttpAttributeRoutes();

            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}/{id2}/{id3}/{id4}/{id5}",
                defaults: new {
                    id = RouteParameter.Optional,
                    id2 = RouteParameter.Optional,
                    id3 = RouteParameter.Optional,
                    id4 = RouteParameter.Optional,
                    id5 = RouteParameter.Optional
                }
            );
        }

As per @Muzaffer Galata comment, you should amend your url to match your end point, see snippet below

$(function () {
    $(".formSubmit").click(function () {
        var cName = $('#cName').val();
        var cSurname = $('#cSurname').val();
        var cEmail = $('#cEmail').val();
        var cMessage = $('#cMessage').val();
        console.log(cMessage);
        console.log(cEmail);
        console.log(cSurname);
        console.log(cName);
        //change below
        if (cName != null && cName != '' && cSurname != null && cSurname != '' && cEmail != null && cEmail != '' && cMessage != null && cMessage != '') {
            $.ajax({
                type: "GET",
                url: "/api/ContactUsApi/Get?cName=" + cName + "&cSurname=" + cSurname + "&cEmail=" + cEmail + "&cMessage=" + cMessage,
                contentType: "json",
                dataType: "json",
                success: function (data) {
                    if (data != null) {

                    }
                },
                error: function (xhr) {
                    alert(xhr.responseText);
                }
            });
        }
    });
});

We solved with @Nikhil Patil

My url is must look like this :

url :"/api/contactusapi/" + cName + "/" + cSurname + "/" + cEmail + "/" + cMessage

Thanks for your comment and help!

Related