FromUri into class - c#

I'm using this code
[Route("{id}/users/{name}"]
[HttpGet]
public string GetUserInfo([FromUri]int id, string name)
{
return this.GetInfo(new User {Id = id, Name = name});
}
Can I use a ([FromUri]Someclass class) in c# in Route like this:
[Route("{id}/users/{name}"]
[HttpGet]
public string GetUserInfo([FromUri]User user)
...
The question is "How can I use [FromUri](or something else)Someclass in thar Route

You can also use [FromBody] attribute to bind the parameter class from the request body.
[Route("{id}/users/{name}"]
[HttpGet]
public string GetUserInfo([FromBody]User user)
...
You can read more about this here.

Related

ASP.NET MVC Attribute routing parameter issue

I have the following code
public class BooksController : Controller
{
[Route("/Books/{id?}")]
public IActionResult Index(string id)
{
return View(id);
}
}
My problem is that when I try to enter the parameter it is (as it seems) considered as controller's action so I keep getting this exception.
I need somebody to explain what am I doing wrong.
If you want to pass some parameter to a view as a string you can make this like below:
public class BooksController : Controller
{
[Route("/Books/{id?}")]
public IActionResult Index(string id)
{
if (string.IsNullOrEmpty(id))
id = "default_value";
return View((object)id);
}
}
If the string type is passing to the View() call without casting to object it will be interpreted as a view name.
And the view model data should be declared as
#model string;
<h2>#Model</h2>
Try changing the route as given below -
[Route("Books", Name = "id")]

Handle WebApi Core methods with Id as string and int

I have two methods:
[HttpGet("{id}")]
public IActionResult GetTask([FromRoute] int id)
{
}
[HttpGet("{userId}")]
public IActionResult GetUserTask([FromRoute] string userId)
{
}
As you can see, i want to pass to my API routes like:
https://localhost:44365/Task/1
and
https://localhost:44365/Task/string
But my WebApi project cant handle it. When i pass route like this:
https://localhost:44365/Task/7dd2514618c4-4575b3b6f2e9731edd61
i get an 400 http and this response:
{
"id": [
"The value '7dd2514618c4-4575b3b6f2e9731edd61' is not valid."
]
}
While debugging, im not hitting any methods (when i pass string instead of int)
My question is, how to verload methods with one parameters with string or int? These methods do diffrent things
EDIT
When i pass something like:
https://localhost:44365/Task/dddd
I still get response with invalid id
You can define parameter type like [HttpGet("{id:int}")]. For more information refer below link.
https://learn.microsoft.com/en-us/aspnet/web-api/overview/web-api-routing-and-actions/attribute-routing-in-web-api-2#route-constraints
Your actions should be like below.
[HttpGet("{id:int}")]
public IActionResult GetTask([FromRoute] int id)
{
}
[HttpGet("{userId}")]
public IActionResult GetUserTask([FromRoute] string userId)
{
}
Use like this
[HttpGet("{id}")]
public IActionResult GetTask([FromRoute] int id)
{
}
[HttpGet("User/{userId}")]
public IActionResult GetUserTask([FromRoute] string userId)
{
}
and while calling api with guid/string use
https://localhost:44365/Task/User/7dd2514618c4-4575b3b6f2e9731edd61

Modify Parameter Binding in ASP.NET Web API via Attribute Usage

My goal is to have a controller with method
I am trying to create an attribute DefaultValue as below:
class ModelClass
{
int modelId;
string modelName;
[DefaultValue("foo")]
string modelString;
}
class ModelClass2
{
string fooBar;
[DefaultValue("bar")]
string otherStringValue;
}
with controller:
[HttpPut]
public async Task<HttpResponseMessage> Put(ModelClass model)
{
...
}
[HttpPost]
public async Task<HttpResponseMessage> Put(ModelClass2 model2)
{
...
}
The way this DefaultValue will work is that when a user passes a value in, if modelString in ModelClass is null or the empty string, this will populate it with "foo" (from the constructor of the attribute).
Else, the user defined value will be used.
The same would be true of otherStringValue in ModelClass2
In ASP.NET MVC it looks like this can be accomplished by using the BindProperty method of a IModelBinder interface, but I can't find anything similar for WebApi

How do I write REST service to support multiple Get Endpoints in .net MVC Web API?

So I am familiar with how to write the default Get, Post, Put, Delete
//GET api/customer
public string Get(){}
//GET api/customer/id
public string Get(int id){}
//POST api/customer
public void Post([FromBody]string value){}
//PUT api/customer/id
public void Put(int id, [FromBody]string value){}
//DELETE api/customer/id
public void Delete(int id){}
But how would I write add another Get endpoint w/o having to create a whole new controller? I want to grab the customer's metadata? do I need to make any changes to the routeConfig? if so how would I do that? and then how would I use the new route in javascript?
//GET api/customer/GetMetaData
public string GetMetaData(){
}
You use the Attribute Route. This attribute was added in WebApi 20 and you can use it at Method level to define new route or more routes and the way you use it is like [Route("Url/route1/route1")]:
Using one of your examples above it will be like:
//GET api/customer/GetMetaData
[Route("api/customer/GetMetaData")]
public string Get2(){
//your code goes here
}
If you will be declaring several Routes in your class then you can use RoutePrefix attribute like [RoutePrefix("url")] at class level. This will set a new base URL for all methods your in Controller class.
For example:
[RoutePrefix("api2/some")]
public class SomeController : ApiController
{
// GET api2/some
[Route("")]
public IEnumerable<Some> Get() { ... }
// GET api2/some/5
[Route("{id:int}")]
public Some Get(int id) { ... }
}
Note: In the example above I showed one example where Route allowed us to set type constraints as well.

Parsing Attribute Routed URL in ASP.Net Web API

I'm trying to get the parameters of specific attribute routed URL on ActionFilterAttribute. For instance I have an action like below:
[Route("/v1/test/{userId}/{udid}")]
public object GetNewObject(int userId, string udid)
And in action filter attribute the absolute url is coming something like "http://test.example.com/v1/test/1/123-asda-231-asd". However I want to parse these parameters as userId=1 and udid=... within a collection.
Is it possible?
Anyway I found the answer,
Within RouteData of ControllerContext we may able to retrieve the specified value.
actionContext.ControllerContext.RouteData.Values["udid"]
[Route("...")] is possible only in MVC 5.
I think you want to do something like this
[RoutePrefix("api/users")]
public class UsersController : ApiController
{
// GET api/users
[Route("")]
public IEnumerable<User> Get() { ... }
// GET api/user/5
[Route("{id:int}")]
public Book Get(int id) { ... }
// POST api/users
[Route("")]
public HttpResponseMessage Post(User book) { ... }
}
where each User contains your properties
public class User
{
int UserId{get;set;}
string Udid{get; set;}
}

Categories