I have the react snippet:
const model = {
Code: 'somecode',
Elements: elements,
...more
}
apiPost(url, false, model)
.then(
)
Then:
export function apiPost(url, addAuth, json) {
return apiFetch('post', url, addAuth, json)
}
function apiFetch(method, url, addAuth, json, file) {
let opts = {
method: method,
headers: {}
}
if (addAuth) {
opts.headers = { ...opts.headers, ...authHeader() }
}
if (json) {
opts.headers = { ...opts.headers, ...{ 'content-type': 'application/json' } }
opts.body = JSON.stringify(json);
}
if (file) {
opts.body = file;
}
return fetch(baseUrl() + url, opts).then(handleResponse)
}
I am receiving it at the api side:
[HttpPost]
public async Task<JsonResult> Post([System.Web.Http.FromBody] SurveyEntry model)
{
try
{
...
}
catch (Exception ex)
{
...
}
}
but the model comes null.
I am puzzled why this happens.
Any suggestions what I am doing wrong?
Related
I try to fetch and recieve data in my net core app.
This code works:
[HttpPost]
public JsonResult Post([FromBody] User user)
{
var s = HttpContext.Request.QueryString;
Console.WriteLine($"name: {user.Name}, age: {user.Age}");
return Json(user);
}
public class User
{
public int Id { get; set; }
public string Name { get; set; }
public int Age { get; set; }
}
const url = "http://localhost:5000/Home/Post";
const user = {Name: 'valenok', Age: 25 };
fetch(url, {
method: 'POST', // or 'PUT'
body: JSON.stringify(user),
headers: {
'Accept': 'application/json; charset=utf-8',
'Content-Type': 'application/json;charset=UTF-8'
}
}).then(res => res.json())
.then(response => console.log('Success:', JSON.stringify(response)))
.catch(error => console.error('Error:', error));
But if I try to send object {file and string} i recieve just a string field ImageDTO.FileName. ImageDTO.Image is null.
Here is the code:
[HttpPost]
public async Task AddFile(ImageDTO img)
{
Console.WriteLine($"FileName: {img.Image}");
Console.WriteLine($"FileName: {img.FileName}");
if (img.Image == null)
{
Console.WriteLine("NULL");
}
try
{
string path = "/Files/" + img.FileName;
using (var fileStream = new FileStream(appEnvironment.WebRootPath + path, FileMode.Create))
{
Console.WriteLine($"IMAGE: {img.Image}");
await img.Image.CopyToAsync(fileStream);
}
return Json($"File saved to{path}");
}
catch (System.Exception ex)
{
Console.WriteLine($"Something wrong! {ex.Message}");
return Json($"Something wrong! {ex.Message}");
}
}
clientside:
class FileDownloadForm1 extends React.Component {
state = {
file: null,
title: null,
};
onFileChange = (e) => {
this.setState({file: e.target.value})
console.log(this.state.file);
};
onTitleChange = (e) => {
this.setState({title: e.target.value})
console.log(this.state.title);
};
onSubmit = async (e) => {
e.preventDefault();
const formData = new FormData();
const url = "http://localhost:5000/Home/AddFile";
formData.append("FileName", this.state.title);
formData.append("Image", this.state.file);
console.log(this.state.file);
console.log(this.state.title);
let xhr = new XMLHttpRequest();
xhr.open('POST', url);
xhr.send(formData);
}
render() {
return (
Choose file to upload
Simplae label
{/* {this.onTitleChange(e)}} name="title">*/}
Submit
);
onSubmit method i tried like this and result was the same:
code>
(with headers or not)
onSubmit = async (e) => {
e.preventDefault();
const formData = new FormData();
const url = "http://localhost:5000/Home/AddFile";
formData.append("FileName", this.state.title);
formData.append("Image", this.state.file);
const result = await fetch(url, {
method: 'POST',
body: formData
});
const response = await result.json();
console.log(response);
}
console output:
FileName: 123
NULL
IMAGE:
Something wrong! Object reference not set to an instance of an object.
I check this How to upload image from React to ASP.NET Core Web API?
but... if i asking it`s not worked for me. help
You can try to use e.target.files[0] to get the selected file, like below.
onFileChange = (e) => {
this.setState({ file: e.target.files[0] });
console.log(this.state.file);
};
I'm getting this error every time I press a specific button on my react-native app. I'm guessing it has to do something with an Api call or maybe it is trying to invoke URLs with localhost:8081, which may not be correct as it should be pointing to a server. I'm not sure exactly how to pinpoint the problem. Any help would be much appreciated. I'm also now sure if the problem is coming from the file I shared underneath.
App Warning message:
This is my RestClient code:
import {Alert, AsyncStorage} from 'react-native'
import {resetRouteTo} from 'util/NavigationHelper'
import {store} from '../index.js'
import {dropdownAlert} from 'util/AlertManager'
const DEFAULT_ERROR = {error: {code: 500, message: 'No JSON message'}}
export default class RestClient {
constructor (baseUrl = '', navigation, { headers = {}, devMode = false, simulatedDelay = 0 } = {}) {
if (!baseUrl) throw new Error('missing baseUrl')
this.navigation = navigation
this.headers = {
'Accept': 'application/json',
'Content-Type': 'application/json'
}
Object.assign(this.headers, headers)
this.baseUrl = baseUrl
this.simulatedDelay = simulatedDelay
this.devMode = devMode
}
_clearTokenAndGo () {
AsyncStorage.removeItem('apiToken')
Alert.alert(
'Error',
'Something went wrong and your account needs to be re-instantiated.',
[
{text: 'OK', onPress: () => resetRouteTo(this.navigation, 'OnboardingFirst')}
],
{ cancelable: false }
)
}
_simulateDelay () {
return new Promise(resolve => {
setTimeout(() => {
resolve()
}, this.simulatedDelay)
})
}
async _parseIfJson (response) {
var contentType = response.headers.get('content-type')
if (contentType && contentType.indexOf('application/json') !== -1) {
return response.json()
}
return null
}
async _handleError (response) {
const body = await this._parseIfJson(response)
if (!body) {
dropdownAlert('error', `Server Error ${response.status}`, 'Something went wrong on the server')
return DEFAULT_ERROR
}
switch (response.status) {
case 200: {
break
}
case 401: {
if (body.error === 'Unauthenticated.') {
this._clearTokenAndGo()
}
break
}
case 400: {
dropdownAlert('error', `Error ${body.error.code}`, body.error.message)
break
}
default: {
if (body.error) {
dropdownAlert('error', `Error ${body.error.code}`, body.error.message)
} else {
dropdownAlert('error', 'Error', `An unknown error has occurred. Http status ${response.status}`)
}
break
}
}
return body
}
_fullRoute (url) {
return `${this.baseUrl}${url}`
}
async _fetch (route, method, body, isQuery = false) {
if (!route) throw new Error('Route is undefined')
if (!store.getState().netinfo.isConnected) {
this.navigation.navigate('BlockScreen')
return {success: false, error: {code: 1, message: 'No internet connection.'}}
}
var fullRoute = this._fullRoute(route)
if (isQuery && body) {
var qs = require('qs')
const query = qs.stringify(body)
fullRoute = `${fullRoute}?${query}`
body = undefined
}
let opts = {
method,
headers: this.headers
}
if (body) {
Object.assign(opts, { body: JSON.stringify(body) })
}
const fetchPromise = () => fetch(fullRoute, opts)
if (this.devMode && this.simulatedDelay > 0) {
// Simulate an n-second delay in every request
return this._simulateDelay()
.then(() => fetchPromise())
.then(response => response.json())
} else {
let promise = await fetch(fullRoute, opts)
console.log('Logging response =>')
console.log(promise)
return this._handleError(promise)
}
}
GET (route, query) { return this._fetch(route, 'GET', query, true) }
POST (route, body) { return this._fetch(route, 'POST', body) }
PUT (route, body) { return this._fetch(route, 'PUT', body) }
DELETE (route, query) { return this._fetch(route, 'DELETE', query, true) }
}
Other files using RestClient:
import RestClient from 'util/RestClientLib'
import qs from 'qs'
import { Linking, AsyncStorage } from 'react-native'
import Config from 'react-native-config'
var SHA256 = require('crypto-js/sha256')
export default class ApiClient extends RestClient {
constructor (authToken, navigation) {
console.log('constructing apiClient with base: ', Config.API_URL)
super(Config.API_URL, navigation, {
headers: {
'Authorization': 'Bearer ' + authToken
}
})
}
_switchSchemeTo (url, scheme) {
var split = url.split(':')
split[0] = scheme
return split.join(':')
}
_makeAppUrl (url) {
const prefix = url.split('.')[0]
const bank = prefix.substr(prefix.lastIndexOf('/') + 1, prefix.length)
switch (bank) {
case 'florijnbank':
return this._switchSchemeTo(url, 'flrb')
default:
return url
}
}
async _openUrl (url) {
const openInApp = await AsyncStorage.getItem('openInApp')
const appUrl = this._makeAppUrl(url)
Linking.canOpenURL(appUrl).then(supported => {
if (!supported || openInApp !== 'true') {
Linking.canOpenURL(url).then(supported => {
if (!supported) {
console.log('Can\'t handle url: ' + url)
} else {
Linking.openURL(url)
}
}).catch(err => console.error('An error occurred', err))
} else {
Linking.openURL(appUrl)
}
}).catch(err => console.error('An error occurred', err))
}
async createToken (pin) {
var hash = SHA256(pin).toString()
const query = {pincode: hash}
let response = await this.POST('/user', query)
return response.api_token
}
async checkPin (pin) {
const hash = SHA256(pin).toString()
const query = {pincode: hash}
return this.GET('/user/validate', query)
}
getAccounts () {
return this.GET('/account')
}
getBalance (iban) {
return this.GET(`/account/${iban}`)
}
async getPermissionBank (bank) {
const query = {
bank_id: bank
}
let response = await this.POST('/account', query)
return this._openUrl(response.url)
}
postCredentialsAis (form) {
return this.POST('/account/password', form)
}
async ais (iban) {
let response = await this.GET(`/ais/${iban}`)
if (response.url == null) {
return true
}
this._openUrl(response.url)
return false
}
getTransactionDetails (requestId) {
return this.GET(`/request/${requestId}`)
}
getTransactions (iban) {
return this.GET(`/account/${iban}/transaction`)
}
getContacts () {
return this.GET('/contacts')
}
getSettings () {
return this.GET('/startup')
}
deleteAccount (iban) {
return this.DELETE(`/account/${iban}`)
}
/**
* async submitTransfer - submits a transfer
*
* #param {Object} options object which holds the pin, iban, sso and query
* #param {Object} transfer hold the transfer information
* #return {Boolean} either opens a link or a boolean for success
*/
submitTransfer (iban, credentials, transfer) {
const url = `/account/${iban}/transaction?${qs.stringify(credentials)}`
const body = {
counter_iban: transfer.counterIban,
counter_account_name: transfer.name,
amount: transfer.amount,
description: transfer.description,
reference: transfer.reference
}
return this.POST(url, body)
}
qrConfirmTransfer (transactionId, iban, credentials) {
const url = `/request/${transactionId}/confirm/${iban}?${qs.stringify(credentials)}`
return this.POST(url)
}
directConfirmTransfer (transactionId, iban, form) {
const url = `/account/${iban}/transaction/${transactionId}`
return this.POST(url, form)
}
verificationRequired (iban, amount) {
const query = {amount: amount}
return this.GET(`/veriReq/${iban}`, query)
}
};
there:
I am want to send some data
here is the code : filename:[wx-resource.ts]
import {Promise} from 'es6-promise';
declare const wx: any;
class WxResource {
public socketOpen: boolean = false;
public count: number = 0;
public socketState;
public reqObj: any = {
url: 'http://192.168.8.138/api/v1/user/auth/status',
token: "eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE0ODcxMjg0MjcsImxldmVsIjoiIiwidWlkIjoiZTE3MmQ0NGUtZGY5Ni00NzBjLTlmM2QtMWJkN2RlNjU3MTA0In0.BG2w-Lo02i2xaga4iZkM7RmP8hXgpRKAC-0MTp5hFj_ugnwATt2m9nDjtmJfRpWnAlpfmXZLgEQTlMHwG2H9hhoqojJC6piCh76UkH0mNwjJrBGiTINurholwTF2VYQPysB4bz7G4jepzEccNdD_NW-_Rxw-Bo5WDcH37OZ2zTw"
};
constructor() {
this.listen().connect().afterConnect();
}
private listen(): WxResource {
let _that = this;
wx.onSocketOpen((event) => {
console.info('WebSocket已打开:', event);
this.count++;
this.socketState = event.target.readyState;
this.socketOpen = true;
// this.sendMsg(_that.reqObj,"GET");
console.log("open的次数:", this.count);
return this.socketOpen;
});
wx.onSocketError((event) => {
console.error('WebSocket连接打开失败,请检查!', event);
});
// console.log("外部:", this.socketOpen);
return this;
}
private connect(): WxResource {
wx.connectSocket({
url: "ws://192.168.8.138/api/ws"
});
return this;
}
private afterConnect(resolve?, reject?): WxResource {
wx.onSocketMessage((res) => {
console.log("服务器返回:", JSON.parse(res.data));
resolve(JSON.parse(res.data));
});
return this;
}
//发送消息
private sendMsg(reqObj, method?) {
console.log("socketState: ", this.socketState); //undefined
if (!this.socketOpen) {
console.log("webSocket opened");
// 判断是否传入token
let header = {};
if (reqObj.token === undefined) {
console.log("no token");
header = {
"S-Request-Id": Date.now() + Math.random().toString(20).substr(2, 6)
}
} else if (reqObj.token !== undefined) {
console.log("get token");
header = {
"S-Request-Id": Date.now() + Math.random().toString(20).substr(2, 6),
"Authentication": "Bearer " + reqObj.token
}
}
wx.sendSocketMessage({
data: JSON.stringify({
"method": method,
"url": reqObj.url,
"header": header,
"body": JSON.stringify(reqObj.data)
}),
success: function (res) {
console.log("发送成功", res)
},
fail: function (res) {
console.log("发送失败", res)
}
});
} else {
console.log("socket not open", this.socketOpen);
}
}
public get() {
let _that = this;
console.log("socketOpen", this.socketOpen);
this.sendMsg(this.reqObj, "GET");
return new Promise((resolve, reject) => {
_that.afterConnect(resolve, reject);
})
}
}
export default WxResource;
then I'm import above code like this:
import WxResource from '../../utils/wx-resource'
and use it
const wxResource = new WxResource();
wxResource.get();
and something went wrong:
here is the console:
"sendSocketMessage:fail Failed to execute 'send' on 'WebSocket': Still in CONNECTING state."
I just want to call wx.onSocketOpen (), and then by calling the get method when using wx.sendSocketMessage to send data to the server,method POST, DELETE the same, without calling wx.onSocketOpen () again; I don't know where is wrong, please point out, thank you
Hi I have code that has a column Date in Linq.
when I call this code behind function using ajax it return the date column as "/Date(1464710400000)/"
How can I handle this??
This is my code:
function SetSubsVal() {
$.ajax({
type: "POST",
url: "AccountManagement.aspx/GetModeofPayment",
data: '{ptype: true, regid:' + $("#hdnRegID").val() + '}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (result) {
if (result.d.length != 0) {
$(result.d).each(function (i, data) {
try { $('#subsType').val(data.SubscriptionType.toString()); } catch (err) { }
try { $('#subscriptionfee').val(data.Fee.toString()); } catch (err) { }
try { $('#invRcptSub').val(data.InvoiceRecipient.toString()); } catch (err) { }
try {
debugger;
$('#invDateSub').val(data.InvoiceDate);
} catch (err) { }
try { $('#startDateSub').val(data.StartDate.toString()); } catch (err) { }
try { $('#endDateSub').val(data.EndDate.toString()); } catch (err) { }
try { $('#numberoforder').val(data.NumberOfOrder.toString()); } catch (err) { }
try { $('#ordersleft').val(data.OrderLeft.toString()); } catch (err) { }
try {
if (data.Active) {
prevSettup[0].SubsActive = '1';
$('#lblActive').trigger('click');
}
} catch (err) { }
})
}
}
,
error: function (err) {
alert(err.responseText);
}
});
}
Here my code behind:
[WebMethod]
[System.Web.Script.Services.ScriptMethod(ResponseFormat = System.Web.Script.Services.ResponseFormat.Json)]
public static List<AccountPaymentMode> GetModeofPayment(bool ptype, int regid)
{
List<AccountPaymentMode> payments = new List<AccountPaymentMode>();
using (EDMEntities entity = new EDMEntities())
{
payments = entity.AccountPaymentModes.Where(w => w.RegID == regid && w.IsSubscription == ptype).ToList();
}
return payments;
}
I'm working on an ASP MVC application, in one page I try to make an AJAX request using jQuery and I get this error (in Firefox):
SyntaxError: JSON.parse: unexpected character.
This is my JavaScript function:
function deleteGoal(id) {
var dataget = { "goalId": id };
$.ajax({
type: "GET",
url: '#Url.Action("DeleteGoal", "Goals")',
data: dataget,
dataType: "json",
success: function (json) {
if (json.isValid == false) {
Growl.error({
title: 'Error sending messages',
text: json.error
});
return false;
}
else {
alert("success");
}
},
error: function (xhr, status, error) {
alert(error);
},
});
}
which is called in the following way:
<a class="btn btn-red" id="delete_#val.Id" onclick="javascript:deleteGoal('#val.Id')">#ViewBag.Translator.Translate("Delete")</a>
The ID passed as the parameter is a GUID.
This is the controller's full code:
class GoalsController : BaseController
{
private const string ErrorViewPath = "../Shared/Error";
public ActionResult Goals(Guid? nodeId = null, string groupByCriteria = "Type", string sortCriteria = "LastModified")
{
try
{
ViewBag.Translator = SessionManager.Translator;
ViewBag.NodeId = nodeId;
if (!IsUserLogged())
{
return RedirectToAction("Login","Account");
}
if (!IsUserRegistered())
{
return RedirectToAction("Register", "Account", null);
}
if (SessionManager.UserStatus < (long)UserStatus.AmwayInitialized)
{
return RedirectToAction("Activation", "Account");
}
var res = Proxy.GetGoals(nodeId == null ? (Guid)SessionManager.NodeId : (Guid)nodeId);
if (res.HasErrors)
{
return ReportErrors(res, ErrorViewPath);
}
if (res.Value.Count == 0)
{
return View(new List<IGrouping<object,GoalContract>>());
}
ViewBag.groupBy = groupByCriteria;
ViewBag.sortBy = sortCriteria;
PropertyInfo sortPinfo = res.Value[0].GetType().GetProperty(sortCriteria);
PropertyInfo groupPinfo = res.Value[0].GetType().GetProperty(groupByCriteria);
res.Value.Sort(new Comparison<GoalContract>((x, y) => CompareGoalContract(x, y, sortPinfo)));
var groups = res.Value.GroupBy(g => g.GetType().GetProperty(groupByCriteria).GetValue(g));
return View(groups);
}
catch (Exception ex)
{
return ReportErrors(ex, ErrorViewPath);
}
}
private int CompareGoalContract(GoalContract t1, GoalContract t2, PropertyInfo property)
{
IComparable v1 = (IComparable)property.GetValue(t1);
IComparable v2 = (IComparable)property.GetValue(t2);
return v1.CompareTo(v2);
}
public ActionResult EditGoals(Guid? nodeId, string groupByCriteria = "Type", string sortCriteria = "LastModified")
{
try
{
ViewBag.Translator = SessionManager.Translator;
if (!IsUserLogged())
{
return RedirectToAction("Login", "Account");
}
if (!IsUserRegistered())
{
return RedirectToAction("Register", "Account", null);
}
if (SessionManager.UserStatus < (long)UserStatus.AmwayInitialized)
{
return RedirectToAction("Activation", "Account");
}
var res = Proxy.GetGoals(nodeId == null ? (Guid)SessionManager.NodeId : (Guid)nodeId);
if (res.HasErrors)
{
return ReportErrors(res, ErrorViewPath);
}
if (res.Value.Count == 0)
{
return View(new List<IGrouping<object, GoalContract>>());
}
ViewBag.groupBy = groupByCriteria;
ViewBag.sortBy = sortCriteria;
PropertyInfo sortPinfo = res.Value[0].GetType().GetProperty(sortCriteria);
PropertyInfo groupPinfo = res.Value[0].GetType().GetProperty(groupByCriteria);
res.Value.Sort(new Comparison<GoalContract>((x, y) => CompareGoalContract(x, y, sortPinfo)));
var groups = res.Value.GroupBy(g => g.GetType().GetProperty(groupByCriteria).GetValue(g));
return View(groups);
}
catch (Exception ex)
{
return ReportErrors(ex, ErrorViewPath);
}
}
[HttpPost]
[AllowAnonymous]
public ActionResult SaveGoal(GoalContract contract)
{
try
{
contract.LastModified = DateTime.UtcNow;
var result = Proxy.SaveGoal(contract);
return Json(new { error = result.PrintErrors(), isValid = !result.HasErrors});
}
catch (Exception ex)
{
return Json(new { error = ex.Message, isValid = false, isException = true });
}
}
[HttpPost]
public ActionResult DeleteGoal(Guid goalId)
{
try
{
var result = Proxy.DeleteGoal(goalId);
return Json(new { error = result.PrintErrors(), isValid = !result.HasErrors, isException = false }, JsonRequestBehavior.AllowGet);
}
catch (Exception ex)
{
return Json(new { error = ex.Message, isValid = false, isException = true }, JsonRequestBehavior.AllowGet);
}
}
}
Please change
$.ajax({
type: "GET",
url: '#Url.Action("DeleteGoal", "Goals")',
to
$.ajax({
type: "POST",
url: '#Url.Action("DeleteGoal", "Goals")',
and if you don't want to do a post then from the action remove attribute
[HttpPost]
so that your action looks like
public ActionResult DeleteGoal(Guid goalId)
{
try
{
var result = Proxy.DeleteGoal(goalId);
return Json(new { error = result.PrintErrors(), isValid = !result.HasErrors, isException = false }, JsonRequestBehavior.AllowGet);
}
catch (Exception ex)
{
return Json(new { error = ex.Message, isValid = false, isException = true }, JsonRequestBehavior.AllowGet);
}
}
Hope that helps.