ASP.NET WebApi custom route - asp.net

I have a simple Controller that is returning thumbnails, it is defined like:
public class ThumbnailsController : ApiController
{
public HttpResponseMessage Get(string id)
{
//code here
}
}
Everything works fine, I can access image using url http://site.com/api/Thumbnails/mylogin
But I would like to modify this method like so:
public class ThumbnailsController : ApiController
{
public HttpResponseMessage Get(string login="", int size=64)
{
//code here
}
}
Idea is to be able to call:
- http://site.com/api/Thumbnails/ - this will return current logged in user picture in default (64x64) size
- http://site.com/api/Thumbnails/mylogin - this will return mylogin user picture in default (64x64) size
- http://site.com/api/Thumbnails/mylogin/128 - this will return mylogin user picture in 128x128 size
My problem are routes, default route works with my unchanged method, but how should I change the default to get this working?
I will also have other Api Controllers but only this one should have custom route.
Here is my attempt, but it isn't working.
routes.MapHttpRoute(
name: "Thumbnails",
routeTemplate: "api/thumbnails/{login}/{size}",
defaults: new {controller="Thumbnails", action="Get", login = RouteParameter.Optional, size = RouteParameter.Optional }
);
EDIT
This is my Controller with test method:
public class ThumbnailsController : ApiController
{
public string Get(string login="", int size=64)
{
return string.Format("login: {0}, size: {1}", login, size);
}
}
and here is my RouteConfig:
public class RouteConfig
{
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}
);
routes.MapHttpRoute(
name: "Thumbnails",
routeTemplate: "api/Thumbnails/{login}/{size}",
defaults: new { controller = "Thumbnails" , login = RouteParameter.Optional, size = RouteParameter.Optional }
);
}
}

Make sure you declare your custom route before the default route in the WebApiConfig.
EDIT:
public static void Register(HttpConfiguration config)
{
config.Routes.MapHttpRoute(
name: "Thumbnails",
routeTemplate: "api/Thumbnails/{login}/{size}",
defaults: new { controller = "Thumbnails", action = "Get",
login = RouteParameter.Optional, size = RouteParameter.Optional }
);
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}

The custom route should be before the default one
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapHttpRoute(
name: "Thumbnails",
routeTemplate: "api/Thumbnails/{login}/{size}",
defaults: new { controller = "Thumbnails" , login = RouteParameter.Optional, size = RouteParameter.Optional }
);
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new {controller = "Home", action = "Index", id = UrlParameter.Optional}
);
}
And try to change the type of the "size" to nullable integer:
public HttpResponseMessage Get(string login = null, int? size = 64)

Related

ASP.NET Root Url Doesn't Resolve to Default.aspx

I have an asp.net web site that won't seem to resolve to Default.aspx when initially loading. When I debug on my local machine it loads Default no problem. Unless I try to navigate to "localhost:#####/". Then it gives a 404 error. When I deploy it to a staging server, give it a virtual path "mywebapp", and load it from "mydomain.com/mywebapp" it gives a 404 as well. I have set Default.aspx to the top of the list for Default Document in IIS. If I navigate to "mydomain.com/mywebapp/default" the site loads just fine. Any suggestions? I would paste code but it is a large website and I quite honestly am not sure what I'm looking for anymore.
EDIT:
In my site I am also using DataTables for display and edit of data. In the ajax calls I was previously able to call the controller by using urls such as:
api/MyController/idvalue
but since uncovering this I had to go back and preface the urls to get them to work:
mywebapp/api/MyController/idvalue
Controller:
public class MyController : ApiController
{
[Route("api/MyContoller/{idvalue}")]
[HttpGet]
[HttpPost]
public IHttpActionResult MyControllerMethod(intidvalue)
{
}
}
WebApiConfig:
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
}
RouteConfig:
public static class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
var settings = new FriendlyUrlSettings();
settings.AutoRedirectMode = RedirectMode.Permanent;
routes.EnableFriendlyUrls(settings);
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
//routes.MapRoute(
// name: "Default",
// url: "{controller}/{action}/{id}",
// defaults: new { action = "Index", id = UrlParameter.Optional }
// );
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
}
Found the solution. In my RouteConfig.cs if I comment out the line:
controller = "Home",
it works just fine.
public static class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
var settings = new FriendlyUrlSettings();
settings.AutoRedirectMode = RedirectMode.Permanent;
routes.EnableFriendlyUrls(settings);
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
//routes.MapRoute(
// name: "Default",
// url: "{controller}/{action}/{id}",
// defaults: new { action = "Index", id = UrlParameter.Optional }
// );
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new
{
//controller = "Home",
action = "Index",
id = UrlParameter.Optional
}
);
}
}
However, I'm not completely sure why this is. So if anyone is able to explain it to me that would be great!

"Message":"The requested resource does not support http method 'GET'." error

I have configured routing like this:
config.Routes.MapHttpRoute(
name: "Sales",
routeTemplate: "api/{Sales}/{jsonresponce}",
defaults: new { controller = "Sales", action = "Postsomething" }
);
config.Routes.MapHttpRoute(
name: "User",
routeTemplate: "api/{User}/{GetDetails}",
defaults: new { controller = "User", action = "GetDetails" }
);
Here is my UserController:
public class UserController : ApiController
{
userservice objservice = new userservice();
[HttpGet]
public CustDetails GetDetails(string Username, string Password, string BillingFeedID)
{
CustDetails model = new CustDetails();
//checking for encrypted password
model.UserName = Username;
model.Password = Password;
model.BillingFeedID = BillingFeedID;
model = objservice.Login(model);
//taking merchant configuration data
var data = objservice.Getcustomerconfig(model.MerchantID, BillingFeedID);
model.LastPosBillID = data.LastPosBillID;
model.LastTimeStamp = data.LastTimeStamp;
model.SyncStatus = data.SyncStatus;
model.SynsTimeInterval = data.SynsTimeInterval;
model.DataSorce = data.DataSorce;
model.DataAuthentication = data.DataAuthentication;
model.DataBaseQuery = data.DataBaseQuery;
return model;
}
}
I also have a SalesController:
public class SalesController : ApiController
{
[HttpPost]
public async Task<HttpResponseMessage> PostSomething()
{
StringBuilder sb = new StringBuilder();
try
{
string jsonData = await Request.Content.ReadAsStringAsync();
// dynamic dataList = JArray.Parse(jsonData);
if (File.Exists(#"C:\MCarrots\Umairbills\Umairbills.json"))
File.Delete(#"C:\MCarrots\Umairbills\Umairbills.json");
File.Create(#"C:\MCarrots\Umairbills\Umairbills.json").Close();
File.WriteAllText(#"C:\MCarrots\Umairbills\Umairbills.json", jsonData);
return Request.CreateResponse(HttpStatusCode.OK, "OK");
}
catch (Exception ex)
{
File.WriteAllText(#"C:\MCarrots\mcarrots\Umairbills.json", ex.ToString());
return Request.CreateResponse(HttpStatusCode.NoContent, ex.ToString());
}
}
When I try to call the GetUserDetails action with this url:
http://localhost:42945/api/User/GetDetails?Username=kay001&Password=kay501&BillingFeedID=KF1
It is throwing this error:
"Message":"The requested resource does not support http method"
But the POST method in SalesController is working.
Your route templates seem off. I think they should be:
config.Routes.MapHttpRoute(
name: "Sales",
routeTemplate: "api/Sales/{action}",
defaults: new { controller = "Sales", action = "Postsomething" }
);
config.Routes.MapHttpRoute(
name: "User",
routeTemplate: "api/User/{action}",
defaults: new { controller = "User", action = "GetDetails" }
);
I changed the route templates so that the controller name is essentially hard-coded, and the action is a placeholder. The action can be left out in this case though, defaulting to GetDetails.

Show custom url?

How to display custom url and not based on controller and action names?
My routing looks like
public class RouteConfig
{
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 }
);
routes.MapRoute(
name: "productfeature",
url: "cn/pendrive/18-gb",
defaults: new { controller = "Product", action = "Feature", id = UrlParameter.Optional }
);
}
}
and my link button looks like
<li>#Html.RouteLink("Product Feature", "productfeature")</li>
I get url as the Url mentioned in the code but i also 404 error.
http://localhost:9090/cn/pendrive/18-gb
How to go for static urls? Basically my aim is to no show controllers and action names in url.
Put your custom route before the default one:
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "productfeature",
url: "cn/pendrive/18-gb",
defaults: new { controller = "Product", action = "Feature", id = UrlParameter.Optional }
);
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}

ASP.NET MVC URL Routing with ControllerName/ExampleID

i'm getting this error when i'm navigate browser to url:
localhost:10793/RealEstates/10
this my RouteConfig code:
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}",
defaults: new { controller = "Main", action = "Index" }
);
routes.MapRoute(
name: "RealEstates",
url: "RealEstates/{action}",
defaults: new { controller = "RealEstates", action = "Index" }
);
routes.MapRoute(
name: "RealEstatesViewAd",
url: "RealEstates/{id}",
defaults: new { controller = "RealEstates", action = "ViewAd", id = UrlParameter.Optional }
);
}
}
my error:
Description: HTTP 404. The resource you are looking for (or one of its dependencies) could have been removed, had its name changed, or is temporarily unavailable. Please review the following URL and make sure that it is spelled correctly.
when changed code to:
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
//routes.MapRoute(
// name: "Default",
// url: "{controller}/{action}",
// defaults: new { controller = "Main", action = "Index" }
//);
//routes.MapRoute(
// name: "RealEstates",
// url: "RealEstates/{action}",
// defaults: new { controller = "RealEstates", action = "Index" }
//);
routes.MapRoute(
name: "RealEstatesViewAd",
url: "RealEstates/{id}",
defaults: new { controller = "RealEstates", action = "ViewAd", id = UrlParameter.Optional }
);
}
}
it's work but when i call on other actions in controller
localhost:10793/RealEstates/CreateAd
this error found
The parameters dictionary contains a null entry for parameter 'id' of
non-nullable type 'System.Int32' for method
'System.Web.Mvc.ActionResult ViewAd(Int32)' in
'Youe3lan.Controllers.RealEstatesController'. An optional parameter
must be a reference type, a nullable type, or be declared as an
optional parameter.
Parameter name: parameters
and this my controller:
namespace MvcAppliction1.Controllers
{
public class RealEstatesController : Controller
{
public ActionResult Index()
{
return View();
}
public ActionResult ViewAd(int id)
{
return View();
}
public ActionResult CreateAd()
{
return View();
}
}
}
You need to change it to:
routes.MapRoute(
name: "RealEstatesViewAd",
url: "RealEstates/{action}/{id}",
defaults: new { controller = "RealEstates", action = "ViewAd", id UrlParameter.Optional }
);}}
Have a look here it might help:
http://msdn.microsoft.com/en-us/library/cc668201(v=vs.100).aspx
UPDATE
Add this to your controller:
public ActionResult ViewAd(Int32 id)
{
return View();
}
You see
localhost:10793/RealEstates/10
is translated to:
localhost:10793/RealEstates/ViewAdd/10
So you need that method in the controller accepting an it parameter.
you've flagged your id in your route as optional:
id = UrlParameter.Optional
but I bet your controller isn't nullable??
public ActionResult ViewAd(Int32 id)
{
}
So you cant post a null into your id even though the route allows it. If you change this to:
public ActionResult ViewAd(Int32? id)
{
}
You won't get the error message:
The parameters dictionary contains a null entry for parameter 'id' of
non-nullable type 'System.Int32' for method
'System.Web.Mvc.ActionResult ViewAd(Int32)' in
'Youe3lan.Controllers.RealEstatesController'. An optional parameter
must be a reference type, a nullable type, or be declared as an
optional parameter. Parameter name: parameters

WebAPI No action was found on the controller

I got an error - No action was found on the controller 'Action' that matches the request.
The url is http://localhost:37331/api/action/FindByModule/1.
The routing I used is
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{action}/{id}",
defaults: new { id = RouteParameter.Optional }
);
Controller:
public class ActionController : ApiController
{
private IActionRepository repository = null;
[HttpGet]
[ActionName("All")]
public IEnumerable<JsonAction> All()
{
return from action in this.repository.Get()
select new JsonAction
{
ID = action.ID,
Text = action.Text.Trim(),
Description = action.Description.Trim(),
};
}
[HttpGet]
[ActionName("FindByModule")]
public IEnumerable<JsonAction> FindByModule(Int64 moduleId)
{
return from action in this.repository.FindByModule(moduleId)
select new JsonAction
{
ID = action.ID,
Text = action.Text.Trim(),
Description = action.Description.Trim(),
};
}
}
This is because there is a parameter name mismatch. From your route the value 1 is assigned to parameter named id and your action is looking for parameter named moduleId.
First option is to change your route like this:
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{action}/{moduleId}",
defaults: new { moduleId = RouteParameter.Optional }
);
Second is to change your URL like this:
http://localhost:37331/api/action/FindByModule?moduleId=1
So the parameter name match.
My api had too many parameters and I was getting an error. I solved the problem with Route.
[Route("addressverification/{id}/{no}/{day}/{month}/{year}")]
public AdressVerificationResult Get(long? id, long? no ,long? day, long? month, long? year)
{
return new AdressVerificationResult
{
Aciklama = "19........4 kimlik numaralı kişinin 18.......1 adres numarasında 'YerlesimYeri' adres tipi için geçerli bir yurtiçi adres beyanı mevcuttur.",
DurumKod = true
};
}

Resources