Allowing parameter name to have "[" in ASP.Net Core WEB API - asp.net-web-api

My action method should look like:
public IActionResult GetAll([FromQuery]string page[Number],[FromQuery]string page[Size])
{
//code
}
HTTP Request is like: "GetAll?page%5Bnumber%5D=0&page%5Bsize%5D=100".
Problem : the parameter name doesn't allow me to have a square bracket.

Besides, that I'd go for simpler names of the parameters, you can solve this by using a dictionary:
public IActionResult GetAll(Dictionary<string, string> page) {
var x = page["Number"];
var y = page["Size"];
}

Related

DataSourceRequest is not deserializing for a WebAPI Get method

I am trying to call a WebAPI method from Angular 5 like this:
selectClaims(state: DataSourceRequestState):Observable<DataResult>
{
return this.http.get<GridDataResult>(`${this.apiUrl}/SelectClaims?${toDataSourceRequestString(state)}`);
}
Which calls the API method as expected. The API method is:
[Route("SelectClaims")]
[HttpGet]
public IHttpActionResult SelectClaims([FromUri][DataSourceRequest]DataSourceRequest ClaimsRequest)
{
if(ClaimsRequest == null)
ClaimsRequest=new DataSourceRequest { Page=1, PageSize=20 };
var result = _db.Claims.ToDataSourceResult(ClaimsRequest, c => { c.SortHistory(); return c; });
return Ok(result);
}
The trouble is that ClaimsRequest only de-serializes Page and PageSize correctly. Filters and Sorts don't come through:
Fiddler tells me that the URL from Angular is:
GET /api/v1/Claims/SelectClaims?filter=id~eq~2&page=1&sort=firstName-asc&pageSize=20 HTTP/1.1, but in the controller both filter and sort are null.
If I create a URL through Swagger like: 'http://localhost:50223/api/v1/Claims/SelectClaims?ClaimsRequest.page=1&ClaimsRequest.pageSize=11&ClaimsRequest.sorts=firstName-desc' I do see a sort array in the API method, but the "Member" field is null.
Any attempt to add a filter through Swagger like 'http://localhost:50223/api/v1/Claims/SelectClaims?ClaimsRequest.page=1&ClaimsRequest.pageSize=11&ClaimsRequest.filters=id~eq~2' results in a "Cannot create an instance of an interface." error.
The state is a DataSourceRequestState in the angular component from a Kendo Grid for Angular.
I have simulated this in a simple test program and everything works fine there. The only difference in my test program is that the API controller targets .Net Core and the real system targets .Net 4.6.1.
Do I have to de-serialize manually in .Net 4.6.1 for some reason, or is something else going on here?
It should be a POST not a GET. Something like this:
return this.http.post<GridDataResult>(`${this.apiUrl}/SelectClaims`, toDataSourceRequestString(state)});
I needed it to be a GET (URL) so i created a new object
public class GridParamaterBinder
{
public int Page { get; set; }
public int PageSize { get; set; }
public string Filter { get; set; }
public string Sort { get; set; }
public DataSourceRequest ToDataSourceRequest(IConfigurationProvider mapper, Func<string, string> OverDefaultParamaterMapping)
{
DataSourceRequest result = new DataSourceRequest();
result.Page = Page;
result.PageSize = PageSize;
result.Sorts = GridDescriptorSerializer.Deserialize<SortDescriptor>(Sort);
result.Filters = FilterDescriptorFactory.Create(Filter);
return result;
}
}
and used it instead of the Telerik effort.
in API I Bind it like so
public virtual DataSourceResult Get([FromUri]GridParamaterBinder request)
And then used it like
DataSourceResult results = query.ToDataSourceResult(request.ToDataSourceRequest(), r => (r)));
Thanks #KevDevMan for your solution. I found this example,
then I changed my API controller like this and it worked like a charm :
[HttpGet, Route("for-kendo-grid")]
public DataSourceResult GetProducts([System.Web.Http.ModelBinding.ModelBinder(typeof(WebApiDataSourceRequestModelBinder))] DataSourceRequest request)
explanation here

IHttpActionResult and helper methods in ASP.NET Core

I'm trying to move my web api 2 project to ASP.NET 5.
But I have many elements that are not present anymore.
For example IHttpActionResult or Ok(), NotFound() methods.
Or RoutePrefix[]
Should I change every IHttpActionResult with IActionResult ?
Change Ok() with new ObjectResult ? (is it the same ?)
What about HttpConfiguration that seems no more present in startup.cs ?
IHttpActionResult is now effectively IActionResult, and to return an Ok with a return object, you'd use return new ObjectResult(...);
So effectively something like this:
public IActionResult Get(int id)
{
if (id == 1) return HttpNotFound("not found!");
return new ObjectResult("value: " + id);
}
Here's a good article with more detail:
http://www.asp.net/vnext/overview/aspnet-vnext/create-a-web-api-with-mvc-6
Updated reply-ish
I saw that someone referenced the WebApiCompatShim in a comment.
WebApiCompatShim is still maintained for this kind of portability scenarios and it is now released 1.1.0.
I saw that Microsoft.AspNetCore.OData 1.0.0-rtm-00011 has WebApiCompatShim as a dependency. I don't know exactly what they are trying to achieve in this area, these are just facts.
If you're not into getting another compatibility package and you're looking into more refactoring work, you can look at the following approach: WebApiCompatShim - how to configure for a REST api with MVC 6
You will still be able to use Ok() or you can try to use the OkObjectResult() method as Http word was removed in order not to be too verbose. HttpOkObjectResult -> OkObjectResult
[HttpPost]
public ObjectResult Post([FromBody]string value)
{
var item = new {Name= "test", id=1};
return new OkObjectResult(item);
}
[HttpPost]
public ObjectResult Post([FromBody]string value)
{
var item = new {Name= "test", id=1};
return Ok(item);
}
At 2.2, the ASP.NET Core migration guide states to replace IHttpActionResult with ActionResult. This works for me:
[Produces("application/json")]
[HttpPost]
public ActionResult GetSomeTable([FromBody] GridState state)
{
return Ok(new
{
data = query.ToList(),
paging = new
{
Total = total,
Limit = state.limit,
page = state.page,
Returned = query.Count()
}
});
}

How do you read POST data in an ASP.Net MVC 3 Web API 2.1 controller?

This does not seem to be as easy as I thought. I found some solutions on the web, but they are not working for me. I have an ASP.Net MVC 3 project with the Microsoft ASP.Net Web API 2.1 nuget package installed. Now, I want to be able to read data posted to a web api controller. The data sent will vary, so I cannot used a strongly typed ViewModel.
Here are the solutions I tried:
public void Post([FromBody]string value)
{
...
}
public void Post([FromBody]List<string> values)
{
...
}
public void Post([FromBody]NameValueCollection values)
{
...
}
But my value or values variables are always empty. I know the controller is receiving data however because I can check it by accessing (System.Web.HttpContextWrapper)Request.Properties["MS_HttpContext"].Request.Form. It does not look like the proper way to retrieve the data though. There ought to be a cleaner way.
UPDATE:
Here is how I am posting the information:
I am posting the data from another controller in the same web application:
public ActionResult SendEmailUsingService()
{
dynamic email = new ExpandoObject();
email.ViewName = "EmailTest";
email.From = "fromaddress#yahoo.com";
email.To = "toaddress#gmail.com";
email.Fullname = "John Smith";
email.Url = "www.mysite.com";
IDictionary<string, object> data = email;
using (var wb = new WebClient())
{
string url = BaseUrlNoTrailingSlash + Url.RouteUrl("DefaultApi", new { httproute = "", controller = "Emailer" });
var response = wb.UploadValues(url, "POST", data.ToNameValueCollection());
}
return View();
}
And here is what I am getting in my Post web api controller if I declare an httpContext variable like this:
var httpContext = (System.Web.HttpContextWrapper)Request.Properties["MS_HttpContext"];
httpContext.Request.Form =
{ViewName=EmailTest&From=fromaddress%40yahoo.com&To=toaddress%40gmail.com&Fullname=John+Smith&Url=www.mysite.com}
httpContext.Request.Form is a System.Collections.Specialized.NameValueCollection {System.Web.HttpValueCollection}
I finally found the answer to my question here:
Web API Form Data Collection
The solution is to use FormDataCollection:
public void Post([FromBody]FormDataCollection formData)
{
...
}

How to send an array via a URI using Attribute Routing in Web API?

I'm following the article on Attribute Routing in Web API 2 to try to send an array via URI:
[HttpPost("api/set/copy/{ids}")]
public HttpResponseMessage CopySet([FromUri]int[] ids)
This was working when using convention-based routing:
http://localhost:24144/api/set/copy/?ids=1&ids=2&ids=3
But with attribute routing it is no longer working - I get 404 not found.
If I try this:
http://localhost:24144/api/set/copy/1
Then it works - I get an array with one element.
How do I use attribute routing in this manner?
The behavior you are noticing is more related to Action selection & Model binding rather than Attribute Routing.
If you are expecting 'ids' to come from query string, then modify your route template like below(because the way you have defined it makes 'ids' mandatory in the uri path):
[HttpPost("api/set/copy")]
Looking at your second question, are you looking to accept a list of ids within the uri itself, like api/set/copy/[1,2,3]? if yes, I do not think web api has in-built support for this kind of model binding.
You could implement a custom parameter binding like below to achieve it though(I am guessing there are other better ways to achieve this like via modelbinders and value providers, but i am not much aware of them...so you could probably need to explore those options too):
[HttpPost("api/set/copy/{ids}")]
public HttpResponseMessage CopySet([CustomParamBinding]int[] ids)
Example:
[AttributeUsage(AttributeTargets.Parameter, Inherited = false, AllowMultiple = false)]
public class CustomParamBindingAttribute : ParameterBindingAttribute
{
public override HttpParameterBinding GetBinding(HttpParameterDescriptor paramDesc)
{
return new CustomParamBinding(paramDesc);
}
}
public class CustomParamBinding : HttpParameterBinding
{
public CustomParamBinding(HttpParameterDescriptor paramDesc) : base(paramDesc) { }
public override bool WillReadBody
{
get
{
return false;
}
}
public override Task ExecuteBindingAsync(ModelMetadataProvider metadataProvider, HttpActionContext actionContext,
CancellationToken cancellationToken)
{
//TODO: VALIDATION & ERROR CHECKS
string idsAsString = actionContext.Request.GetRouteData().Values["ids"].ToString();
idsAsString = idsAsString.Trim('[', ']');
IEnumerable<string> ids = idsAsString.Split(',');
ids = ids.Where(str => !string.IsNullOrEmpty(str));
IEnumerable<int> idList = ids.Select(strId =>
{
if (string.IsNullOrEmpty(strId)) return -1;
return Convert.ToInt32(strId);
}).ToArray();
SetValue(actionContext, idList);
TaskCompletionSource<object> tcs = new TaskCompletionSource<object>();
tcs.SetResult(null);
return tcs.Task;
}
}

What is wrong with this ASP.Net and Fiddler example?

I am using Visual Studio 2012 RC. I am using the default routes and have the following Web API controller:
public class FooController : ApiController
{
// GET api/foo
public IEnumerable<string> Get()
{
return new string[] { "value1", "value2" };
}
// GET api/foo/5
public string Get(int id)
{
return "value";
}
// POST api/foo
public string Post(string abc)
{
Console.WriteLine("value: {0}", abc);
return "foo" + abc;
}
// PUT api/foo/5
public void Put(int id, string value)
{
}
// DELETE api/foo/5
public void Delete(int id)
{
}
}
I wanted to do a simple test of POST in Fiddler, so I have
Request Headers
User-Agent: Fiddler
Content-Type: application/json
Request Body
{"abc": "def"}
When I debug the request, the parameter abc comes in as null, not "def". Is there something wrong with my Fiddler syntax?
(1) By default, simple types are taken from the URI. To read a simple type from the request body, add the [FromBody] attribute to the parameter.
public string Post([FromBody] string abc)
(2) '{"abc": "def"}' defines an object with a property named "abc" - to send a JSON string, the request body should just be "def"
This answer comes from a link on the ASP.Net Web API site sending-html-form-data , which turns out to be Mike's blog post (I didn't realize that at first). The Web API team has made a few decisions with parameter binding that are quite different from normal MVC controllers.
The correct syntax for sending "simple types" is
public HttpResponseMessage PostSimple([FromBody] string value)
{
// code goes here
And in Fiddler, you put
=def //THIS CANNOT HAVE QUOTES AND = IS MANDATORY
OK, so here are the parts that work very differently from MVC.
You must use [FromBody], as Mike says.
You can only have 1 parameter. If you want more than 1 parameter, you have 2 choices: i) use url query parameters, instead of request body or ii) use a complex object (i.e. your own class).
The request body should be a simple =def and cannot use named parameters.

Resources