I have a simple ASP.NET Core MVC controller action method defined as:
public class MyMVCController : Controller
{
public async Task<IActionResult> MyAction(String usrid)
{
// ...
}
}
When I call it using this URI:
https://localhost:6009/MyMVC/MyAction/073214df
My action gets invoked and I get return back, but the parameter usrid is always null. What am I doing wrong?
UPDATE
#Jackdaw's first solution, change parameter name from usrid to id worked for me. However, the ones with attributes don't. While the parameter does get passed in, the action will fail because the accessToken somehow returns null in the line below. This is not the case in the first solution.
[Route("MyMVC/MyAction/{usrid?}")]
public async Task<IActionResult> MyAction(String usrid)
{
var accessToken = await HttpContext.GetTokenAsync("access_token");
var client = new HttpClient();
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
// ...
}
Finally, I figured out how to get the attribute based routing solutions to work - adding another attribute [Authorize] to the action method. Don't ask me why I have to do this and why I don't in the usrid/id solution.
It`s because the default route pattern has the following definition:
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
});
Therefore, if change the method parameter name to id it will work:
public async Task<IActionResult> MyAction(String id)
Or you can apply the following route attribute to the method:
[Route("MyMVC/MyAction/{usrid?}")]
public async Task<IActionResult> MyAction(String usrid)
{
// ...
}
Test screenshot:
I am Creating a new Web API Controller named Customer.
and this Controller has one Action named "Create"
I couldn't make this Action able to be requested via "GET" HTTP Request
in this form
http://ip:port/api/Customer/Create?userId=x&password=y
except in this method :
public class CustomerController : ApiController
{
[System.Web.Mvc.AcceptVerbs("GET", "POST")]
[System.Web.Mvc.HttpGet]
[ActionName("Create")]
public MISApiResult<List<Branch>> GetCreate(string userID, string password)
{
return new MISApiResult<List<Branch>>() { Result = new List<Branch>() { new Branch() { ID = Guid.NewGuid(), Name = "Branch1" } }, ResultCode = 1, ResultMessage = "Sucess" };
}
}
Is there any other solution to preserve the action name as "Create" as next.
public class CustomerController : ApiController
{
[System.Web.Mvc.AcceptVerbs("GET", "POST")]
[System.Web.Mvc.HttpGet]
public MISApiResult<List<Branch>> Create(string userID, string password)
{
return new MISApiResult<List<Branch>>() { Result = new List<Branch>() { new Branch() { ID = Guid.NewGuid(), Name = "Branch1" } }, ResultCode = 1, ResultMessage = "Sucess" };
}
}
Thanks.
Edit:
Sorry for not being clear at the first time.
According to this answer:
How does a method in MVC WebApi map to an http verb?
There is a default http method according to the action names, if it starts with Get it'll bemapped to GET HTTP Method be default otherwise it will be mapped to POST.
Is there a way to change this default mapping with a custom one so I could map an action named "Create" with "GET" Http Method for testing purpose since this way is faster for development
I tried to put HttpGet Attribute and AcceptVerbs("GET") and it still map the action with POST Http method.
I found a way like I said and it's to change the action method name into GetCreate and then put ActionName attribute with "Create" value.
but is there a way to change the default mapping?
Thanks again.
You can use custom route fore this action:
[HttpGet]
[Route("customer/create")]
public MISApiResult<List<Branch>> Create(string userID, string password)
Don't forget to enable attribute routing during application configuration (this should be added before default route definition):
config.MapHttpAttributeRoutes();
Though I would recommend to follow the conventions and use appropriate HTTP verbs - if you are creating a customer, then by convention you should use POST request to endpoint api/customers. Otherwise your API can be confusing for other people.
Also I would recommend to use IHttpActionResult as the return type of your method:
public IHttpActionResult Post(string userID, string password)
{
if (_userRepository.Exists(userID))
return BadRequest($"User with ID {userID} already exists");
_userRepository.Create(userID, password);
return StatusCode(HttpStatusCode.Created) // or CreatedAtRoute
}
Further reading: Attribute Routing in ASP.NET Web API 2
why dont you specify route. You actual issue is using System.Web.Mvc
use System.Web.Http instead
using System.Web.Http;
[RoutePrefix("api/Customer")]
public class CustomerController : ApiController
{
[HttpGet]
[Route("Create")]
public MISApiResult<List<Branch>> Create(string userID, string password)
{
return new MISApiResult<List<Branch>>() { Result = new List<Branch>() { new Branch() { ID = Guid.NewGuid(), Name = "Branch1" } }, ResultCode = 1, ResultMessage = "Sucess" };
}
}
I have a simple API with basic routing. It was setup using the default Visual Studio 2015 ASP.NET Core API template.
I have this controller and action:
[Route("api/[controller]")]
public class DocumentController : Controller
{
[HttpGet("info/{Id}")]
public async Task<Data> Get(string Id)
{
//Logic
}
}
So to reach this method, I must call GET /api/document/info/some-id-here.
Is it possible with .NET Core, inside that method, to retrieve as a string the complete route?
So I could do for example:
var myRoute = retrieveRoute();
// myRoute = "/api/document/info/some-id-here"
You can get the complete requested url using the Request option (HttpRequest) in .Net Core.
var route = Request.Path.Value;
Your final code.
[Route("api/[controller]")]
public class DocumentController : Controller
{
[HttpGet("info/{Id}")]
public async Task<Data> Get(string Id)
{
var route = Request.Path.Value;
}
}
Result route: "/api/document/info/some-id-here" //for example
You can also ask MVC to create a new route URL based on the current route values:
[Route("api/[controller]")]
public class DocumentController : Controller
{
[HttpGet("info/{Id}")]
public async Task<Data> Get(string Id)
{
//Logic
var myRoute = Url.RouteUrl(RouteData.Values);
}
}
Url.RouteUrl is a helper method that lets you build a route URL given any route values. RouteData.Values gives you the route values for the current request.
If you want the original route template on an API controller that was specified with any HttpMethod attribute then this will do it:
var routeAttribute = Url.ActionContext.ActionDescriptor.EndpointMetadata.First(d => d is HttpMethodAttribute);
var routeTemplate = ((HttpMethodAttribute)routeAttribute).Template;
If the original route attribute was: [HttpGet("Self/{id}")]
The routeTemplate value would be: "Self/{id}"
Url.ActionContext.ActionDescriptor.AttributeRouteInfo.Template
"v{version}/{cardId}/cardsTest" {$1}
Right now, my API controller has 2 methods: one to get ALL events, and one to get ONE event.
namespace HobbsEventsMobile.Controllers
{
public class EventController : ApiController
{
// GET api/event
[HttpGet]
public List<HobbsEventsMobile.Models.Event> Get()
{
return HobbsEventsMobile.Models.Event.GetEventSummary();
}
// GET api/event/5
[HttpGet]
public HobbsEventsMobile.Models.Event Get(int id)
{
return HobbsEventsMobile.Models.Event.GetEventDetails(id);
}
}
}
Newly requested functionality requires me to add a way to call events for the current week. I have a stored proc and a method to call this, but I am not sure how to specify the URL. I would like to add this:
[HttpGet]
public List<HobbsEventsMobile.Models.Event> Get()
{
return HobbsEventsMobile.Models.Event.GetThisWeeksEvents();
}
but make it accessible at m.mydomain.com/api/event/thisweek (or something). How do I do that?
You have two different options depending on what version of ASP.NET Web API you're running. If you're on version one you can simply follow the convention based routing and use:
public class EventController : ApiController
{
[HttpGet]
public List<HobbsEventsMobile.Models.Event> ThisWeek()
{
return HobbsEventsMobile.Models.Event.GetThisWeeksEvents();
}
}
You will also need to modify your route definitions to support an action name (by default the framework picks the method based upon the HTTP verb):
config.Routes.MapHttpRoute(
"DefaultApiWithId",
"api/{controller}/{id}",
new { id = RouteParameter.Optional }, new { id = #"\d+" }
);
config.Routes.MapHttpRoute(
"DefaultApiWithAction",
"api/{controller}/{action}"
);
config.Routes.MapHttpRoute(
"DefaultApiGet",
"api/{controller}",
new { action = "Get" },
new { httpMethod = new HttpMethodConstraint("GET") }
);
If you're using version two, you can still use the convention based routing, but you also have the ability to use attribute routing:
public class EventController : ApiController
{
[HttpGet]
[Route("event/thisweek")]
public List<HobbsEventsMobile.Models.Event> ICanNameThisWhateverIWant()
{
return HobbsEventsMobile.Models.Event.GetThisWeeksEvents();
}
}
I'm converting from the WCF Web API to the new ASP.NET MVC 4 Web API. I have a UsersController, and I want to have a method named Authenticate. I see examples of how to do GetAll, GetOne, Post, and Delete, however what if I want to add extra methods into these services? For instance, my UsersService should have a method called Authenticate where they pass in a username and password, however it doesn't work.
public class UsersController : BaseApiController
{
public string GetAll()
{
return "getall!";
}
public string Get(int id)
{
return "get 1! " + id;
}
public User GetAuthenticate(string userName, string password, string applicationName)
{
LogWriter.Write(String.Format("Received authenticate request for username {0} and password {1} and application {2}",
userName, password, applicationName));
//check if valid leapfrog login.
var decodedUsername = userName.Replace("%40", "#");
var encodedPassword = password.Length > 0 ? Utility.HashString(password) : String.Empty;
var leapFrogUsers = LeapFrogUserData.FindAll(decodedUsername, encodedPassword);
if (leapFrogUsers.Count > 0)
{
return new User
{
Id = (uint)leapFrogUsers[0].Id,
Guid = leapFrogUsers[0].Guid
};
}
else
throw new HttpResponseException("Invalid login credentials");
}
}
I can browse to myapi/api/users/ and it will call GetAll and I can browse to myapi/api/users/1 and it will call Get, however if I call myapi/api/users/authenticate?username={0}&password={1} then it will call Get (NOT Authenticate) and error:
The parameters dictionary contains a null entry for parameter 'id' of non-nullable type 'System.Int32' for method 'System.String Get(Int32)' in 'Navtrak.Services.WCF.NavtrakAPI.Controllers.UsersController'. An optional parameter must be a reference type, a nullable type, or be declared as an optional parameter.
How can I call custom method names such as Authenticate?
By default the route configuration follows RESTFul conventions meaning that it will accept only the Get, Post, Put and Delete action names (look at the route in global.asax => by default it doesn't allow you to specify any action name => it uses the HTTP verb to dispatch). So when you send a GET request to /api/users/authenticate you are basically calling the Get(int id) action and passing id=authenticate which obviously crashes because your Get action expects an integer.
If you want to have different action names than the standard ones you could modify your route definition in global.asax:
Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{action}/{id}",
defaults: new { action = "get", id = RouteParameter.Optional }
);
Now you can navigate to /api/users/getauthenticate to authenticate the user.
This is the best method I have come up with so far to incorporate extra GET methods while supporting the normal REST methods as well. Add the following routes to your WebApiConfig:
routes.MapHttpRoute("DefaultApiWithId", "Api/{controller}/{id}", new { id = RouteParameter.Optional }, new { id = #"\d+" });
routes.MapHttpRoute("DefaultApiWithAction", "Api/{controller}/{action}");
routes.MapHttpRoute("DefaultApiGet", "Api/{controller}", new { action = "Get" }, new { httpMethod = new HttpMethodConstraint(HttpMethod.Get) });
routes.MapHttpRoute("DefaultApiPost", "Api/{controller}", new {action = "Post"}, new {httpMethod = new HttpMethodConstraint(HttpMethod.Post)});
I verified this solution with the test class below. I was able to successfully hit each method in my controller below:
public class TestController : ApiController
{
public string Get()
{
return string.Empty;
}
public string Get(int id)
{
return string.Empty;
}
public string GetAll()
{
return string.Empty;
}
public void Post([FromBody]string value)
{
}
public void Put(int id, [FromBody]string value)
{
}
public void Delete(int id)
{
}
}
I verified that it supports the following requests:
GET /Test
GET /Test/1
GET /Test/GetAll
POST /Test
PUT /Test/1
DELETE /Test/1
Note That if your extra GET actions do not begin with 'Get' you may want to add an HttpGet attribute to the method.
I am days into the MVC4 world.
For what its worth, I have a SitesAPIController, and I needed a custom method, that could be called like:
http://localhost:9000/api/SitesAPI/Disposition/0
With different values for the last parameter to get record with different dispositions.
What Finally worked for me was:
The method in the SitesAPIController:
// GET api/SitesAPI/Disposition/1
[ActionName("Disposition")]
[HttpGet]
public Site Disposition(int disposition)
{
Site site = db.Sites.Where(s => s.Disposition == disposition).First();
return site;
}
And this in the WebApiConfig.cs
// this was already there
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
// this i added
config.Routes.MapHttpRoute(
name: "Action",
routeTemplate: "api/{controller}/{action}/{disposition}"
);
For as long as I was naming the {disposition} as {id} i was encountering:
{
"Message": "No HTTP resource was found that matches the request URI 'http://localhost:9000/api/SitesAPI/Disposition/0'.",
"MessageDetail": "No action was found on the controller 'SitesAPI' that matches the request."
}
When I renamed it to {disposition} it started working. So apparently the parameter name is matched with the value in the placeholder.
Feel free to edit this answer to make it more accurate/explanatory.
Web Api by default expects URL in the form of api/{controller}/{id}, to override this default routing. you can set routing with any of below two ways.
First option:
Add below route registration in WebApiConfig.cs
config.Routes.MapHttpRoute(
name: "CustomApi",
routeTemplate: "api/{controller}/{action}/{id}",
defaults: new { id = RouteParameter.Optional }
);
Decorate your action method with HttpGet and parameters as below
[HttpGet]
public HttpResponseMessage ReadMyData(string param1,
string param2, string param3)
{
// your code here
}
for calling above method url will be like below
http://localhost:[yourport]/api/MyData/ReadMyData?param1=value1¶m2=value2¶m3=value3
Second option
Add route prefix to Controller class and Decorate your action method with HttpGet as below.
In this case no need change any WebApiConfig.cs. It can have default routing.
[RoutePrefix("api/{controller}/{action}")]
public class MyDataController : ApiController
{
[HttpGet]
public HttpResponseMessage ReadMyData(string param1,
string param2, string param3)
{
// your code here
}
}
for calling above method url will be like below
http://localhost:[yourport]/api/MyData/ReadMyData?param1=value1¶m2=value2¶m3=value3
In case you're using ASP.NET 5 with ASP.NET MVC 6, most of these answers simply won't work because you'll normally let MVC create the appropriate route collection for you (using the default RESTful conventions), meaning that you won't find any Routes.MapRoute() call to edit at will.
The ConfigureServices() method invoked by the Startup.cs file will register MVC with the Dependency Injection framework built into ASP.NET 5: that way, when you call ApplicationBuilder.UseMvc() later in that class, the MVC framework will automatically add these default routes to your app. We can take a look of what happens behind the hood by looking at the UseMvc() method implementation within the framework source code:
public static IApplicationBuilder UseMvc(
[NotNull] this IApplicationBuilder app,
[NotNull] Action<IRouteBuilder> configureRoutes)
{
// Verify if AddMvc was done before calling UseMvc
// We use the MvcMarkerService to make sure if all the services were added.
MvcServicesHelper.ThrowIfMvcNotRegistered(app.ApplicationServices);
var routes = new RouteBuilder
{
DefaultHandler = new MvcRouteHandler(),
ServiceProvider = app.ApplicationServices
};
configureRoutes(routes);
// Adding the attribute route comes after running the user-code because
// we want to respect any changes to the DefaultHandler.
routes.Routes.Insert(0, AttributeRouting.CreateAttributeMegaRoute(
routes.DefaultHandler,
app.ApplicationServices));
return app.UseRouter(routes.Build());
}
The good thing about this is that the framework now handles all the hard work, iterating through all the Controller's Actions and setting up their default routes, thus saving you some redundant work.
The bad thing is, there's little or no documentation about how you could add your own routes. Luckily enough, you can easily do that by using either a Convention-Based and/or an Attribute-Based approach (aka Attribute Routing).
Convention-Based
In your Startup.cs class, replace this:
app.UseMvc();
with this:
app.UseMvc(routes =>
{
// Route Sample A
routes.MapRoute(
name: "RouteSampleA",
template: "MyOwnGet",
defaults: new { controller = "Items", action = "Get" }
);
// Route Sample B
routes.MapRoute(
name: "RouteSampleB",
template: "MyOwnPost",
defaults: new { controller = "Items", action = "Post" }
);
});
Attribute-Based
A great thing about MVC6 is that you can also define routes on a per-controller basis by decorating either the Controller class and/or the Action methods with the appropriate RouteAttribute and/or HttpGet / HttpPost template parameters, such as the following:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNet.Mvc;
namespace MyNamespace.Controllers
{
[Route("api/[controller]")]
public class ItemsController : Controller
{
// GET: api/items
[HttpGet()]
public IEnumerable<string> Get()
{
return GetLatestItems();
}
// GET: api/items/5
[HttpGet("{num}")]
public IEnumerable<string> Get(int num)
{
return GetLatestItems(5);
}
// GET: api/items/GetLatestItems
[HttpGet("GetLatestItems")]
public IEnumerable<string> GetLatestItems()
{
return GetLatestItems(5);
}
// GET api/items/GetLatestItems/5
[HttpGet("GetLatestItems/{num}")]
public IEnumerable<string> GetLatestItems(int num)
{
return new string[] { "test", "test2" };
}
// POST: /api/items/PostSomething
[HttpPost("PostSomething")]
public IActionResult Post([FromBody]string someData)
{
return Content("OK, got it!");
}
}
}
This controller will handle the following requests:
[GET] api/items
[GET] api/items/5
[GET] api/items/GetLatestItems
[GET] api/items/GetLatestItems/5
[POST] api/items/PostSomething
Also notice that if you use the two approaches togheter, Attribute-based routes (when defined) would override Convention-based ones, and both of them would override the default routes defined by UseMvc().
For more info, you can also read the following post on my blog.
See this article for a longer discussion of named actions. It also shows that you can use the [HttpGet] attribute instead of prefixing the action name with "get".
http://www.asp.net/web-api/overview/web-api-routing-and-actions/routing-in-aspnet-web-api
Web APi 2 and later versions support a new type of routing, called attribute routing. As the name implies, attribute routing uses attributes to define routes. Attribute routing gives you more control over the URIs in your web API. For example, you can easily create URIs that describe hierarchies of resources.
For example:
[Route("customers/{customerId}/orders")]
public IEnumerable<Order> GetOrdersByCustomer(int customerId) { ... }
Will perfect and you don't need any extra code for example in WebApiConfig.cs.
Just you have to be sure web api routing is enabled or not in WebApiConfig.cs , if not you can activate like below:
// Web API routes
config.MapHttpAttributeRoutes();
You don't have to do something more or change something in WebApiConfig.cs. For more details you can have a look this article.
Just modify your WebAPIConfig.cs as bellow
Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{action}/{id}",
defaults: new { action = "get", id = RouteParameter.Optional });
Then implement your API as bellow
// GET: api/Controller_Name/Show/1
[ActionName("Show")]
[HttpGet]
public EventPlanner Id(int id){}