Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get valid url for Web API method with RoutePrefix in the javascript

WebApiConfig

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

Global.asax

Protected Sub Application_Start(sender As Object, e As EventArgs)
    AreaRegistration.RegisterAllAreas()
    GlobalConfiguration.Configure(AddressOf WebApiConfig.Register)
    RouteConfig.RegisterRoutes(RouteTable.Routes)
    FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters)
    BundleConfig.RegisterBundles(BundleTable.Bundles)
End Sub

Web API controller

<Authorize()>
<RoutePrefix("api/customer")>
Public Class CustomerController
   Inherits ApiController

    <Route("saveName")>
    <HttpPost>
    Public Function saveName(value As MyTypeOfValues) As IHttpActionResult
        'Do some staff
    End Function

End Class

Request method:

  var actionurl = "api/customer/saveName";
  $.ajax(actionurl,
  {
     dataType: "JSON",
     data: customerdata,
     type: "POST",
     contentType: "application/json; charset=utf-8",
     error: function() { alert('error');}
  }).done(function (result) { alert(result);});

with url = api/customer/saveName request was sended to http://localhost/MySiteName/Customer/ShowCustomer/api/customer/saveName
and get Error 404

with url = /api/customer/saveName request was sended to http://localhost/api/customer/saveName
and get Error 404

with url = http://localhost/MySiteName/api/customer/saveName which I manually create and send by Fiddler - work fine.

In the different answers of the related questions suggested urls didn't work in my case

Question: How I can generate valid url for Web API request in the javascript/typescript?

like image 317
Fabio Avatar asked Nov 27 '25 06:11

Fabio


1 Answers

Since you want http://localhost/MySiteName/api/customer/saveName you need everthing after the host name ... starting with the trailing slash:

url = /MySiteName/api/customer/saveName

Note: I highly recommend looking into generating typescript code to call these instead of hand typing these on the server and duplicating on the client. Just a point of failure you really can do without.

like image 192
basarat Avatar answered Nov 28 '25 18:11

basarat



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!