How to use asp.net routing C#? - c#

Can anybody help me with this link?
[Route("api/[controller]")]
public class AuthController : ControllerBase
{
private readonly IAuthService _auth;
public AuthController(IAuthService auth)
{
_auth = auth;
}
[HttpGet("getuser/{sessionGuid}")]
public IActionResult Get(Guid sessionGuid)
{
\\code
}
How should the URL be written in order to get to public IActionResult Get(Guid sessionGuid)?

The Route("api/[controller]") attribute you have given your Controller tells the framework to use the name of the Controller as part of the route.
In this case you have an AuthController so all the routes in this Controller will be prefixed with api/auth/.
Additionally you've specified to the framework to map you Get method to the "getuser/{sessionGuid}" route (where sessionGuid is some Guid).
Putting this together the URL you need to call is api/auth/getuser/{sessionGuid}.
All of this needs to be prefixed by the hostname etc. http://localhost:5000/ for example.

Move your route onto the function, and configure it however you'd like.
In my example, it would be: HTTP GET : http://api.com/my/ur/with/as/many/slashses/as/I/want/52
public class AuthController : ControllerBase
{
private readonly IAuthService _auth;
public AuthController(IAuthService auth)
{
_auth = auth;
}
[Route("my/url/with/as/many/slashes/as/I/want/{sessionGuid}")]
[HttpGet("{sessionGuid}")]
public IActionResult Get(Guid sessionGuid)
{
\\code
}
}

Related

Asp net, how to pass a URL as a url paramter

I'm new to ASP Net and I'm having a little trouble passing a URL as a simple parameter.
These are the solutions that I've tried:
[ApiController]
[Route("api/[controller]")]
public class LoginRedditController : ControllerBase
{
[HttpGet("{*longUrl}")]
public ActionResult<string> Get(string longUrl)
{
Console.WriteLine(longUrl);
return "OK";
}
}
This is the URL that I've tried to call:
http://localhost:5001/LoginReddit?longUrl=https://www.reddit.com/r/playmygame/comments/glftsj/stickn_roll_collect_everything_as_you_roll/
I also tried to encode the URL but the result is the same: I got a "ERR_EMPTY_RESPONSE"
This is my second try:
[ApiController]
[Route("api/[controller]")]
public class LoginRedditController : ControllerBase
{
[HttpGet]
public ActionResult<string> Get([FromQuery]string url)
{
Console.WriteLine(longUrl);
return "OK";
}
}
I used the same URL used before but I got the same result.
In my tried try I changed the Route like this:
[Route("api/[controller]/{url}")]
public class LoginRedditController : ControllerBase
{
[HttpGet]
public ActionResult<string> Get([FromQuery]string url)
{
Console.WriteLine(longUrl);
return "OK";
}
}
And I've tried with the following URL:
http://localhost:5001/LoginReddit/https://www.reddit.com/r/playmygame/comments/glftsj/stickn_roll_collect_everything_as_you_roll/
Also encoded but I got the same resoult.
Where is the problem guys?
For a URL like this:
http://localhost:5001/LoginReddit?longUrl=https://www.reddit.com/…
You would write your controller action like this:
[ApiController]
[Route("[controller]")]
public class LoginRedditController : ControllerBase
{
[HttpGet]
public ActionResult<string> Get(string longUrl)
{
Console.WriteLine(longUrl);
return "OK";
}
}
The longUrl string value is automatically taken from the query arguments passed to the route. And the route for the action is combined from that [Route] attribute on the controller and the [HttpGet] attribute on the action.
The Route Attribute specified the format of the url. You missed the "api" part in your url, and it should be like this:
http://localhost:5001/api/LoginReddit?longUrl=https://www.reddit.com/r/playmygame/comments/glftsj/stickn_roll_collect_everything_as_you_roll/
[ApiController]
[Route("api/[controller]")]
public class LoginRedditController : ControllerBase
{
[HttpGet]
public ActionResult<string> Get([FromQuery]string url)
{
Console.WriteLine(longUrl);
return "OK";
}
}

ASP.Net REST API 404

I'm trying to implement a REST API in ASP.Net MVC. This is my code:
[Route("api")]
[ApiController]
public class ContactsController : ControllerBase
{
[HttpGet]
[Produces("application/xml")]
[Route("api/areas/{areaName}/contacts/{contactID}")]
public ActionResult<XmlDocument> Get(string areaName, string contactID)
{
return new XmlDocument();
}
}
However, when I surf to /api/areas/foo/contacts/bar, I encounter HTTP 404.
How can I fix my code?
Note that ActionResult<T> is part of asp.net-core and not the previous asp.net-mvc version. This means that you originally tagged the question incorrectly.
That said, the URL being called does not match the route template of the intended action and thus you will get a not found when trying to call the action.
Reference Routing to controller actions in ASP.NET Core
The provided route has [Route("api")] on the controller and [Route("api/areas/{areaName}/contacts/{contactID}")] on the action, which when combined would result in a URL that looks like
api/api/areas/foo/contacts/bar
I believe the intention was to have api only once so I would suggest remove one of them
Either from the action
[Route("api")]
[ApiController]
public class ContactsController : ControllerBase {
[HttpGet]
[Produces("application/xml")]
//GET api/areas/foo/contacts/bar
[Route("areas/{areaName}/contacts/{contactID}")]
public ActionResult<XmlDocument> Get(string areaName, string contactID) {
return new XmlDocument();
}
}
or removing the prefix on the controller
[ApiController]
public class ContactsController : ControllerBase {
[HttpGet]
[Produces("application/xml")]
//GET api/areas/foo/contacts/bar
[Route("api/areas/{areaName}/contacts/{contactID}")]
public ActionResult<XmlDocument> Get(string areaName, string contactID) {
return new XmlDocument();
}
}

Routing override

I am looking for a way to override action call if some action is present in the controller.
Imagine :
[Route("api/[controller]")]
public partial class UsersController : BaseController {
[HttpGet("Friends/{id}")]
public IActionResult GetFriends(int id) {
// some code
}
then I have in an other file :
[Route("api/[controller]")]
public partial class UsersController : BaseController {
[HttpGet("Friends_custom/{id}")]
public IActionResult GetFriends_custom(int id) {
// some code
}
I want my frontend to only call
/users/friends
How can I get asp route to match the _custom if it exist?
After a long day, I found out we can use Order in the RouteAttribute. it does exactly what I need!

Attribute Routing for querystring

I have below route URL:-
www.domanname.com/subroute/GetInfo?param1=somestring&param2=somestring
I have function in webapi as:-
public class HomeController : ApiController
{
public object GetInfo(string param1,string param2)
{}
}
To apply route:-
[RoutePrefix("subroute")]
public class HomeController : ApiController
{
[Route("GetInfo?param1={param1:string}&param2={param2:string}")]
public object GetInfo(string param1,string param2)
{}
}
But after applying above URL:-
www.domanname.com/subroute/GetInfo?param1=somestring&param2=somestring
It is not able to find that URL
How can I design this particular route?
You need to modify the routes a bit as query string are not normally used in attribute routes. They tend to be used for inline route parameters.
[RoutePrefix("subroute")]
public class HomeController : ApiController {
//Matches GET subroute/GetInfo?param1=somestring&param2=somestring
[HttpGet]
[Route("GetInfo")]
public IHttpActionResult GetInfo(string param1, string param2) {
//...
}
}
Also
Enabling Attribute Routing
To enable attribute routing, call MapHttpAttributeRoutes during configuration. This extension method is
defined in the System.Web.Http.HttpConfigurationExtensions class.
using System.Web.Http;
namespace WebApplication
{
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// Web API routes
config.MapHttpAttributeRoutes();
// Other Web API configuration not shown.
}
}
}
Reference Attribute Routing in ASP.NET Web API 2
[RoutePrefix("subroute")]
public class HomeController : ApiController {
[HttpGet]
[Route("GetInfo/{param1}/{param2}")]
public IHttpActionResult GetInfo(string param1, string param2) {
//...
}
}
Calling
//Matches GET subroute/GetInfo/Hello/World

ASP.Net Web API: How to achieve url parameter and attribute based versioning with same Controller methods

Is it possible to achieve url parameter and attribute based versioning with same Controller methods. To explain that, suppose I have one controller like,
[RoutePrefix("api/{apiVersion:apiVersionConstraint(v2)}/values")]
public class ValuesController : ApiController
{
// GET api/v2/values
[Route("")]
public IEnumerable<string> Get()
{
return new string[] { "v2-value1", "v2-value2" };
}
// GET api/v2/values/5
[Route("{id}")]
public string Get(int id)
{
return "v2-value-" + id;
}
}
Now, I want to access the API endpoint by both of the following URL's:
http://hostname/context/api/v1/values
http://hostname/context/api/values?v=1
Is it possible?
N.B. I'm using the example at WebApiNamespaceVersion in GitHub

Categories