In my project I send post json data object. One item of this object is base64 string. When base63 string is too long, my request doesnt reach to controller. In my opinion , due to length of parameter,it doesnt work. I couldnt find any solition.
[HttpPost]
[ValidateInput(false)]
public ActionResult Add(Page item)
{
if (item == null
|| string.IsNullOrEmpty(item.Title)
|| string.IsNullOrEmpty(item.SeoUrl))
return Content(Serialization.JsonSerialize(new { Status = 400 }));
return Content(Serialization.JsonSerialize(new { Status = 200, Result = PageRepository.Add(item) }));
}
In controller , I wrote code above, in view I wrote code below
var item = {
Title: title,
SeoUrl: seo,
IsActive: isActive,
Portals: portals,
Content: content,
Lang: pageLanguage,
IsShown:isLock,
MetaKeywords:keywords,
MetaDescription:description
}
$.ajax({
type: 'POST',
url: '#Url.Action("Add", "Page")',
data: JSON.stringify(item),
success: function(data) {
if (data.Result !== "SUCCEED") {
if (data.Result == "SEO_URL_EXISTS") {
toastr.warning('Böyle bir seo_url mevcuttur !!!');
return;
}
toastr.error('#Resources.Resource.Error_Unexpected');
return;
}
if (!isActive) {
toastr.success('#Resources.Resource.Success_PageSave');
return;
}
toastr.success('#Resources.Resource.Success_PageSaveAndPublish');
return;
},
error: function(error) {
toastr.error('#Resources.Resource.Error_Unexpected');
return;
},
dataType: "json",
contentType: "application/json; charset=utf-8",
beforeSend: function() {
waitingDialog.show('#Resources.Resource.Waiting_PageUpdating');
},
complete: function() {
waitingDialog.hide();
}
});
In web config I added below,
<system.web.extensions>
<scripting>
<webServices>
<jsonSerialization maxJsonLength="999999999"/>
</webServices>
</scripting>
</system.web.extensions>
content item may include base64 string. How can I send this jason data to controller, even there is long base64 string.
This is error:
Error during serialization or deserialization using the JSON
JavaScriptSerializer. The length of the string exceeds the value set
on the maxJsonLength property. Parameter name: input
Related
I stored images in database in base_64 format. Fetching that data from a controller to html using Ajax. While fetching record from in controller, I get the following error in custom filter exception:
Error during serialization or deserialization using the JSON JavaScriptSerializer. The length of the string exceeds the value set on the maxJsonLength property.
cshtml - Ajax callled:
function imagepop(no) {
$.ajax({
type: "POST",
contentType: 'application/x-www-form-urlencoded;charset=UTF-8',
url:"/Controller/GetImage",
//data: arr,
data: { 'No': no, 'filetype': obj, 'pageNo': pageNo },
//dataType: "json",
success: function (result) {
debugger;
$("#loader_Prcessing").hide();
if (result.Status == "200") {
}
}
});
}
Controller:
public JsonResult GetImage(string no, string filetype, string pageNo)
{
var jsonResult = Json(OutputInfo.lstUploadImgVideoDoc, JsonRequestBehavior.AllowGet);
jsonResult.MaxJsonLength = int.MaxValue;
return Json(jsonResult);
}
web.config:
<system.web.extensions>
<scripting>
<webServices>
<jsonSerialization maxJsonLength="2147483647"/>
</webServices>
</scripting>
</system.web.extensions>
Is there any solution for this at the config level? I don't want to change my code
I'm trying to make an AJAX Request to a method of iActionResult in my ASP.NET application. The request is getting to the method but when its passed along it has a value of null in my method. The value of selectedKommun is always a number when I check it in the console.
$(document).ready(function () {
$('#kommun').change(function () {
var selectedKommun = $("#kommun").val();
var fordonSelect = $('#fordon');
fordonSelect.empty();
if (selectedKommun != null && selectedKommun != '') {
$.ajax({
type: "POST",
url: "/avboka?handler=GetFordon",
beforeSend: function (xhr) {
xhr.setRequestHeader("XSRF-TOKEN",
$('input:hidden[name="__RequestVerificationToken"]').val());
},
data: { "Id": selectedKommun },
contentType: "application/json; charset=utf-8",
dataType: "json"
}).done(function (data) {
console.log(data);
})
}
});
});
Here is my method where im sending my request. I have commended out some code just to check the value of Id.
[HttpPost]
public IActionResult OnPostGetFordon(int Id)
{
//if (!string.IsNullOrWhiteSpace(kommunFordonId) && kommunFordonId.Length == 3)
//{
// IEnumerable<SelectListItem> regions = _fordonRepo.GetFordon(kommunFordonId);
// var json = JsonConvert.SerializeObject(regions);
// return this.Content(json);
//}
//return null;
return new JsonResult(Id);
}
Instead of
contentType: "application/json; charset=utf-8",
try
contentType: "application/x-www-form-urlencoded; charset=UTF-8",
This is because you are not sending JSON content, only an int.
You also don't really need to specify a datatype since you are only sending an int.
UpdateModule is a function used for update module details. It's not a view page.
When click on update, it returns 500 (internal server error) or 404 error
please help to fix it
$.ajax({
type: 'POST',
url: '#Url.Action("ETM_PRODUCTS","UpdateModule")',
//contentType: 'application/json',
datatype: JSON,
data: { 'ModuleID': ModuleID, 'ModuleName': ModuleName, 'ModuleDescription': ModuleDescription },
success: function (data) {
if (data == true) {
alert("Updated Successfully");
}
},
error: function (msg) {
alert("Error")
},
});
c#
public JsonResult UpdateModule(int ModuleID,string ModuleName,string ModuleDescription) {
bool status = true;
PROD_MODULE tabledata = db.PROD_MODULE.Where(x => x.ETM_MODULE_ID == ModuleID)
.FirstOrDefault();
tabledata.NAME = ModuleName;
tabledata.DESCRIPTION = ModuleDescription;
db.SaveChanges();
return Json ( status, JsonRequestBehavior.AllowGet );
}
There is a problem in the way you call Url.Action.
The first parameter is the action and the second the controller.
Here is the documentation : link
I don´t know why my parameter "ParametroFiltro Filtro" is getting null, the other parameters "page" and "pageSize" is getting OK.
public class ParametroFiltro
{
public string Codigo { get; set; }
public string Descricao { get; set; }
}
My ApiController Get method:
public PagedDataModel<ParametroDTO> Get(ParametroFiltro Filtro, int page, int pageSize)
My ajax call:
var fullUrl = "/api/" + self.Api;
$.ajax({
url: fullUrl,
type: 'GET',
dataType: 'json',
data: { Filtro: { Codigo: '_1', Descricao: 'TESTE' }, page: 1, pageSize: 10 },
success: function (result) {
alert(result.Data.length);
self.Parametros(result.Data);
}
});
You are trying to send a complex object with GET method. The reason this is failing is that GET method can't have a body and all the values are being encoded into the URL. You can make this work by using [FromUri], but first you need to change your client side code:
$.ajax({
url: fullUrl,
type: 'GET',
dataType: 'json',
data: { Codigo: '_1', Descricao: 'TESTE', page: 1, pageSize: 10 },
success: function (result) {
alert(result.Data.length);
self.Parametros(result.Data);
}
});
This way [FromUri] will be able to pick up your complex object properties directly from the URL if you change your action method like this:
public PagedDataModel<ParametroDTO> Get([FromUri]ParametroFiltro Filtro, int page, int pageSize)
Your previous approach would rather work with POST method which can have a body (but you would still need to use JSON.stringify() to format body as JSON).
Provide the contentType property when you make the ajax call. Use JSON.stringify method to build the JSON data to post. change the type to POST and MVC Model binding will bind the posted data to your class object.
var filter = { "Filtro": { "Codigo": "_1", "Descricao": "TESTE" },
"page": "1", "pageSize": "10" };
$.ajax({
url: fullUrl,
type: 'POST',
dataType: 'json',
contentType: 'application/json',
data: JSON.stringify(filter),
success: function (result) {
alert(result.Data.length);
self.Parametros(result.Data);
}
});
It's also possible to access POST variables via a Newtonsoft.Json.Linq JObject.
For example, this POST:
$.ajax({
type: 'POST',
url: 'URL',
data: { 'Note': note, 'Story': story },
dataType: 'text',
success: function (data) { }
});
Can be accessed in an APIController like so:
public void Update([FromBody]JObject data)
{
var Note = (String)data["Note"];
var Story = (String)data["Story"];
}
If you append json data to query string, and parse it later in web api side. you can parse complex object too. It's useful rather than post json object, espeicaly in some special httpget requirement case.
//javascript file
var data = { UserID: "10", UserName: "Long", AppInstanceID: "100", ProcessGUID: "BF1CC2EB-D9BD-45FD-BF87-939DD8FF9071" };
var request = JSON.stringify(data);
request = encodeURIComponent(request);
doAjaxGet("/ProductWebApi/api/Workflow/StartProcess?data=", request, function (result) {
window.console.log(result);
});
//webapi file:
[HttpGet]
public ResponseResult StartProcess()
{
dynamic queryJson = ParseHttpGetJson(Request.RequestUri.Query);
int appInstanceID = int.Parse(queryJson.AppInstanceID.Value);
Guid processGUID = Guid.Parse(queryJson.ProcessGUID.Value);
int userID = int.Parse(queryJson.UserID.Value);
string userName = queryJson.UserName.Value;
}
//utility function:
public static dynamic ParseHttpGetJson(string query)
{
if (!string.IsNullOrEmpty(query))
{
try
{
var json = query.Substring(7, query.Length - 7); //seperate ?data= characters
json = System.Web.HttpUtility.UrlDecode(json);
dynamic queryJson = JsonConvert.DeserializeObject<dynamic>(json);
return queryJson;
}
catch (System.Exception e)
{
throw new ApplicationException("can't deserialize object as wrong string content!", e);
}
}
else
{
return null;
}
}
In .NET Core, the HttpClient sets the transfer-encoding: chunked header by default. This can cause the .NET Web API controller parameters to be null.
To get around this, you'll need to set the ContentLength header explicitly:
var json = JsonConvert.SerializeObject(myObject);
var content = new StringContent(json, Encoding.UTF8, "application/json");
content.Headers.ContentLength = json.Length;
var response = await client.PostAsync("http://my-api.com", content);
SO answer if you already know the transfer-encoding header is the issue: How to disable Chunked Transfer Encoding in ASP.Net C# using HttpClient
Related bug which won't be fixed, which gives some insight into the problem: https://github.com/dotnet/runtime/issues/30283
I want to display in a webpage an exception message raised in my .NET code in the error part of an ajax request:
[HttpPost]
[AllowAnonymous]
public virtual ActionResult AuthenticateUser(string somedata)
{
throw new Exception("Ooops!!");
}
JS code:
jQuery(document).ready(function () {
jQuery.ajax(
'#Url.Action("AuthenticateUser")',
{
contentType: "application/json; charset=utf-8",
dataType: "json",
data: {
somedata:somedata
},
success: function (result) {
if (result == 'true') {
window.location = '#Url.Content(Request["returnUrl"])';
}
},
error: function (response) {
var responseJson = jQuery.parseJSON(response.responseText);
$('#errorMessage').text(responseJson.Message);
$('#progress_message').text("");
},
type: 'post'
}
);
});
The error I get in "response" is HTML code and I want to parse it to get the exception message I throw from the server side. So, the better approach I came up with was to return a Json response, but despite specifying "json" as datatype I still receive HTML code in "response", so... what am I doing wrong? Is the problem the "Exception" object I throw from the server side?
The problem is that whenever an exception is thrown in a controller, it will always trigger asp.net's error page and return whatever is configured for the 500 http status code (the default result is the "yellow page of death" which is an html), what you are trying to do is custom error handling and there are several ways of doing it in depth explanation is present in this blog
One way you could do this is by overriding the OnException method:
protected override void OnException(ExceptionContext filterContext)
{
filterContext.Result = Json(new {Message = filterContext.Exception.Message});
filterContext.ExceptionHandled = true;
}
This will replace the default result for an internal server error (500) with a json result containing the error message, which can be obtained like below
jQuery.ajax(
'#Url.Action("AuthenticateUser")',
{
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (result) {
console.log(result);
},
error: function (response) {
var responseJson = jQuery.parseJSON(response.responseText);
console.log(responseJson.Message); //Logs the exception message
},
type: 'post'
});
This will catch errors Controller wise, if you want to do this application wise you will have to go a little deeper on the blog's methods (probably with the "HandleError" Attribute)
In the end I returned JsonResults and handled the message from the view:
Server code:
[HttpPost]
[AllowAnonymous]
public virtual JsonResult AuthenticateUser(string somedata)
{
if (ok)
return new JsonResult() {Data="ok"}
return new JsonResult() {Data= "Missing data blah"}
}
And in javascript:
success: function (result) {
if (result == 'ok') {
window.location = '#Url.Content(Request["returnUrl"])';
return;
}
$('#progress_message').text("");
$('#errorMessage').text(result);
},