Web-Api 400 BadRequest when search parameter is blank - asp.net-mvc-4

I am using web-api with mvc4
I am making searching functionality, in some cases like if i filter data then remove that textbox value and then press search button, need to show whole listing but in my case showing 400 bad request. as search parameter is blank, i know if search parameter blank then it will throw 400 error with web-api.
any one have proper solution then please let me know.
data: "CurrPage=" + JsCurrPage + "&PageSize=" + parseInt(pagesize) + "&BuildTypeName=" + $("#BuildTypeName").val(),
Here in some cases BuildType is blank. when search made
//controller
public HttpResponseMessage GetBuildTypeList(int CurrPage, int PageSize, string BuildTypeName)
{
}
Net -> XHR URL is :
http://{parentURL}/api/BuildTypeWebApi/GetBuildTypeList?CurrPage=1&PageSize=10&BuildTypeName=

public HttpResponseMessage GetBuildTypeList(string BuildTypeName, int CurrPage = 1, int PageSize = 0)
In you business logic you can assume that a PageSize of 0 means all records.

If you allow CurrPage and PageSize to be empty, then you need to accept nullable ints:
public HttpResponseMessage GetBuildTypeList(int? CurrPage, int? PageSize, string BuildTypeName)
Then, you'll update the query so it return the entire list if no filter values are provided.

Related

How to get json parsing error details in POST requests handlers that use FromBody [duplicate]

This question already has answers here:
Where can you find model binding errors in ASP.NET Core MVC?
(2 answers)
Closed 4 years ago.
I am creating a web api that receives data in a POST request in form of a JSON object in the body.
The real DataObj has many more fields so I simplify it to the following to show a specific sample where parsing must fail:
public class DataObj
{
public int Value { get; set; }
}
[HttpPost]
public async Task<IActionResult> SubTables([FromBody] DataObj data)
{
if (data == null)
{
string parsingErrorDetails = "";
// ? how can I check which kind of parsing erros happend?
return BadRequest("Failed to parse JSON with error: " + parsingErrorDetails);
}
..
}
Typically if you post valid JSON data to the service (like { "value": 1 } it just works fine.
But in the above example a valid JSON body would also be one like { "value": 6123456789 } parsing fails because the value exceeds Int32.MaxValue.
In my case the body has an object with several fields which makes it complicated to analyze the problem if I just return 404 Bad Request.
My goal is that I want to be able to report this specific problem back to the caller so that the caller has an easier option to analyze the root cause of the call.
Best without loosing the option to use [FromBody].
Is there a way to query details why the data object was null as in the sample above so that I can report it back to the caller?
I would check values on the setter properties of DataObj, throwing an exception in case the value doesn't fit.
public class DataObj
{
private int myInt;
public int MyInt{
get{ return myInt;}
set
{
if (value > int.MaxValue)
throw new ArgumentException("Invalid value for MyInt");
myInt = value;
}
}

How to handle search parameter in Datatables

I have the following code :
Controller method
public JsonResult GetNonstandardProgram(
int draw,
int start,
int length,
string search = null /* or string search or string[] search = null */
)
Posted data by datatables
...&search%5Bvalue%5D=somethingToSearch&search%5Bregex%5D=false
and I dont know how to handle this part
&search[value]=somethingToSearch
because in Controller passed string parameter 'search' is allways null.
What am I doing wrong ?
I figured it out, solution is to use
[Bind(Prefix = "search[value]")] string search
as parameter input

MVC returns page as a file

I have an mvc4 project and I am getting a weird result. Whenever I sumit a form and fire up a postback, if the entry is correct it redirects me to the success page which is good. But when my input is invalid and it has to return to the same page, to display the error message, it comes up as a downloadable file. Can anybody please tell me what is going on?
<HttpPost()>
Public Function Collection(oColInfo As CollectionInfoVM) As ActionResult
If ModelState.IsValid Then
oColInfo.CollectionDate = DateTime.Now
m_oAppBase.Collection.AddGroupCollection(oColInfo)
Return View("_Success")
Else
ViewData.Add("PaymentTypes", PaymentType.Dictionary.ToSelectList(oColInfo.PaymentType))
ViewData.Add("PaidBy", PaidBy.Dictionary.ToSelectList(oColInfo.PaidBy.ToString()))
Return View(oColInfo)
End If
End Function
EDIT 1 :
I also found out that my controller is returning my view as JSON. That's why IE is asking me if i wanted to download it. Why is my default return type JSON?
EDIT 2 :
The response type is application/json instead of text/html.
EDIT 3 :
It works when I remove the Html.RenderAction("MainMenu", "Menu") from my layout
Controller action looks like this;
Public Function MainMenu() As PartialViewResult
' Let's see if we have an unprocessed turnin from this district
Dim dtDate As Date = DateTime.Now
Dim colDistStatus As List(Of DistrictStatus) = m_oAppBase.TurnIn.GetNextTurnInStatus()
ViewData.Add("DistrictStatus", colDistStatus)
Return PartialView("_MainMenu")
End Function
Why is my default return type JSON?
ActionResult includes JsonResult too.so when you use ActionResult and you post data from ajax ,your default returns Json.
But when my input is invalid and it has to return to the same page
for validate form in client side,you have to use valid method in your script.it validates form in clientside and doesnt post to your action.
JqueryCode:
if ($('form').valid()) {
$.ajax({});
});
Okay, so looking around I found out that there was a partial view on the page with attribute that returns JSON and when I submit the button this get's fired up too and returned to the browser. I removed the HttpPost attribute and it fixed it. sigh

How to find out which records have been filtered out by Queryable attribute?

I have an asp.net web api controller for which I have enabled odata query options. The controller is as follows:
[Queryable(PageSize = 10)]
public IQueryable<MyDTO> Get(string Id)
{
//some code here
}
As obvious from the Queryable attribute, this controller always returns 10 records at a time if there are more than 10 MyDTO's.
How can I find out which 10 records have been returned or which records have been filtered out by odata query option?
All pageSize does is do a Take on the queryable your action returned after the incoming $filter, $orderby, $skip, $top have been applied first. If you want to post-process the items that you return after the query is applied, you can take ODataQueryOptions<MyDTO> as input and manually apply it on the IQueryable
public IQueryable<MyDTO> Get(string Id, ODataQueryOptions<MyDTO> queryOptions)
{
IQueryable<MyDTO> allMyDTOs = GetMyDTOs(Id);
ODataQuerySettings settings = new ODataQuerySettings() { PageSize = 10 };
IQueryable<MyDTO> appliedMyDTOs = queryOptions.ApplyTo(allMyDTOs, settings) as IQueryable<MyDTO>;
return appliedMyDTOs;
}
Here are some samples.
http://www.asp.net/web-api/overview/odata-support-in-aspnet-web-api/supporting-odata-query-options

Rest Sharp Execute<Int> fails due to cast exception

I have this:
public Int32 NumberOfLocationsForCompany(int companyId)
{
var response = _curl.ResetRequest()
.WithPath(LOCATION_URL)
.AddParam("companyId", companyId.ToString())
.RequestAsGet()
.ProcessRequest<Int32>();
return response;
}
that calls this at the end.
public T ProcessRequest<T>() where T : new()
{
var response = _client.Execute<T>(_request);
if (response.ErrorException != null)
{
throw response.ErrorException;
}
return response.Data;
}
but I get this error. I don't get why it's trying to map an int to a collection or why it's Int64 vs the 32 I specified.: Unable to cast object of type 'System.Int64' to type 'System.Collections.Generic.IDictionary`2[System.String,System.Object]'.
When I hit the api directly this is what I get back
<int xmlns="http://schemas.microsoft.com/2003/10/Serialization/">17</int>
I feel it's something I'm not understanding about Rest Sharp. I tell the execute method to expect an Int, it receives and int, but is trying to map it to a collection. Why and where does the collection come from?
I have noticed that when I look into the base response object's Content the appropriate result "17" is present, why can't Rest Sharp find it? and still where is it finding the Collection?
When looking at the response object I found the return value was in Content vs in Data. I found this to be true whenever I was not returning an object or list of objects.
So now when I'm expecting an int, string, bool, etc I use the following and cast the type of the return value:
public string ProcessRequestWithValue()
{
var response = _client.Execute(_request);
if (response.ErrorException != null)
{
throw response.ErrorException;
}
return response.Content;
}
Hope this helps!