UnityWebRequest Get api call returns connection error - api

So I am trying to do the Get method call to retrieve data from api server.The problem I am getting is that in Unity Editor, Both Get and Post method works perfectly fine, but in the webgl build only post method works whereas Get method returns 500 as error code and webrequest.error as Connection Error.Is there any workaround for this.
public IEnumerator GetPlayerData()
{
Debug.Log("This is Working");
string url = "https:my api";
Authorization playerData = new Authorization();
playerData.walletaddress = PlayerPrefs.GetString("Account");
playerData.table = "userdata";
string jsonStringTrial = JsonUtility.ToJson(playerData);
using (UnityWebRequest webRequest = UnityWebRequest.Get(url))
{
Debug.Log("This is also Working");
webRequest.method = UnityWebRequest.kHttpVerbGET;;
webRequest.SetRequestHeader("Content-Type", "application/json");
webRequest.SetRequestHeader("Accept", "application/json");
webRequest.uploadHandler = new UploadHandlerRaw(System.Text.Encoding.UTF8.GetBytes(jsonStringTrial));
yield return webRequest.SendWebRequest();
Debug.Log(jsonStringTrial);
Debug.Log("This was not Working");
Debug.Log("Data we Received : " + webRequest.downloadHandler.text); // this is always emtpy in webgl but works in editor
if(webRequest.result == UnityWebRequest.Result.ProtocolError)
{
Debug.Log(webRequest.result);
Debug.Log("Protocol Error");
Debug.Log(webRequest.error);
Debug.Log("Error Code" + webRequest.responseCode);
}
if (webRequest.result == UnityWebRequest.Result.DataProcessingError)
{
Debug.Log(webRequest.result);
Debug.Log("DataProcessingError");
Debug.Log(webRequest.error);
Debug.Log("Error Code" + webRequest.responseCode);
}
if (webRequest.result == UnityWebRequest.Result.ConnectionError)
{
Debug.Log(webRequest.result);
Debug.Log(webRequest.error);
Debug.Log("ConnectionError");
Debug.Log("Error Code" + webRequest.responseCode);
}
if (webRequest.result == UnityWebRequest.Result.Success)
{
Debug.Log(webRequest.result);
Debug.Log("Error Code" + webRequest.responseCode);
}
if (webRequest.downloadHandler.text == "{}" || string.IsNullOrEmpty(webRequest.downloadHandler.text))
{
MainMenuHandler.Instance.OpenPanel(MainMenuHandler.Instance.playerLoginPanel);
StartCoroutine(nameof(DisplayMessage));
messageField.text = "Creating Player";
}
else
{
var newData = JsonConvert.DeserializeObject<Root>(webRequest.downloadHandler.text);
PlayerPrefs.SetString(playerNamePrefKey, newData.Item.name);
PlayerPrefs.SetInt("PlayerAvatar", newData.Item.character);
StartCoroutine(GetUserBalance());
yield return new WaitForSeconds(2f);
//NetworkManager.Instance.Connect();
StartCoroutine(nameof(DisplayMessage));
messageField.text = "Getting Data";
}
}
}
Browser Console Log

The "correct" way to fix this issue is to have a look why the server is returnig a 500 Error. 500 errors mean that the problem is something on the server and not on the (Unity-)Client.
So it's not really a Unity problem but a Server problem.

Related

File response in asp.net core API

I have searched many times for my problem but I couldn't find any solution.
the problem which faced is I wrote method yesterday in asp.net core API which is return file response as streaming video when I tried to test on my local machine it's working very well, but when uploading it to my VPS server I got the 500 internal server error so please what is the problem.
the following my code which I used:
[HttpPost("youtube")]
public async Task<IActionResult> GetYoutubeVideoURL([FromBody] string url)
{
if (string.IsNullOrEmpty(url))
{
return Ok(new { Error = "Please provide your url for fetch video." });
}
var id = YoutubeClient.ParseVideoId(url);
if (id == null)
{
return Ok(new { Error = "Video id is not available, try again later." });
}
var client = new YoutubeClient(); //This should be initialized in YoutubeController constructor.
var mediaInfoSet = await client.GetVideoMediaStreamInfosAsync(id);
var mediaStreamInfo = mediaInfoSet.Audio.WithHighestBitrate();
var mimeType = $"audio/{mediaStreamInfo.Container.GetFileExtension()}";
var fileName = $"{id}.{mediaStreamInfo.Container.GetFileExtension()}";
return File(await client.GetMediaStreamAsync(mediaStreamInfo), mimeType, fileName, true);
}

Flurl Post Not Returning from Web Api

I've got a Xamarin application using Flurl, with the following post to a Web Api
Xamarin App:
private async Task<LoginResponse> processLogin()
{
try
{
return await "http://192.168.0.12:60257/api/loginapi/Login".WithTimeout(10).PostJsonAsync(new { username = "fsdafsd", password = "gdfgdsf" }).ReceiveJson<LoginResponse>();
}
catch (Exception e)
{
return new LoginResponse { ResponseStatusCode = -1 };
}
}
Web Api:
public LoginResponse Login([FromBody]LoginRequest loginRequest)
{
var result = new LoginResponse();
try
{
var user = this.UserManager.FindAsync(loginRequest.username, loginRequest.password);
if (user != null)
{
result.ResponseStatusCode = 1;
}
else
{
result.ResponseStatusCode = 0;
}
}
catch (Exception e)
{
result.ResponseStatusCode = -1;
}
return result;
}
I can see my Web Api method getting hit, and it returns the expected object type, not my Xamarin application continues to wait on the Flurl Post.
Can anyone advise what I might be doing wrong?
UPDATE:
I have noticed that the following does work, but it's not ideal:
dynamic result = await "http://192.168.0.12:60257/api/loginapi/Login".PostJsonAsync(new { username = "fsdafsd", password = "gdfgdsf" }).ReceiveJson();
Fixed it. For whatever reason, it was the type I was trying to return. Changing the object variable type to "dynamic" fixed this, and allowed me to deserialise the object correctly.
dynamic result = await "http://192.168.0.12:60257/api/loginapi/Login".PostJsonAsync(new { username = "fsdafsd", password = "gdfgdsf" }).ReceiveJson();
Returns a dynamic object with the properties I'd expect in the normal structure.
If anyone can enlighten my why I couldn't do:
LoginRequest result = ...
It'd be appreciated.

Reditect url from the method of notify_url of paypal in mvc

i am using paypal for payment. in paypal i found two type url -
return_url
notify_url
i wan to check the validity after transaction, save some data and then redirect buyer to receipt page with a unique value that is saved in db. that is why i m not using redirect_url
here is my code
[HttpPost]
public ActionResult TestPaypalIpn()
{
var response = new StreamReader(Request.InputStream, System.Text.Encoding.UTF8).ReadToEnd();
var webClient = new WebClient();
string address = "https://www.sandbox.paypal.com/cgi-bin/webscr?cmd=_notify-validate&" + response;
System.IO.File.WriteAllText(#"D:\Streamstech\Content\requestAddress.txt", address);
try
{
string result = webClient.DownloadString(address);
System.IO.File.WriteAllText(#"D:\Streamstech\Content\response.txt", result);
if (result == "VERIFIED")
{
if (Request.Params["payment_status"] == "Completed" && Request.Params["business"] == Request.Params["receiver_email"])
{
var lisenceKey = Request.Params["transaction_subject"];
var userProductLisence = UserProductLisenceRepository.GetConditional(
l => l.LisenceKey == lisenceKey).FirstOrDefault();
if (userProductLisence != null)
{
if (userProductLisence.PaypalTransactionId == null)
{
userProductLisence.PaypalTransactionId = Request.Params["txn_id"];
userProductLisence.PayerEmailForPaypalTransaction = Uri.EscapeUriString(Request.Params["payer_email"]);
UserProductLisenceRepository.Edit(userProductLisence);
return RedirectToAction("Receipt", "Transaction", new { requestId = userProductLisence.LisenceKey });
}
}
}
return RedirectToAction("ShowError", "Transaction", new { errorname = "", errorMessage = "something went wrong, try again later" });
}
return RedirectToAction("ShowError", "Transaction", new { errorname = "verification Problem", errorMessage = "Transaction not verified" });
}
catch (Exception e)
{
System.IO.File.WriteAllText(#"D:\Streamstech\Content\error.txt", e.Message);
return RedirectToAction("ShowError", "Transaction", new { errorname = "Error..!!!", errorMessage = "something went wrong, try again later" });
throw;
}
return null;
}
here i can compare, save data to database.. but it is not redirecting to receipt page.. what is the problem here in code...??
or any suggestion how can i do it.. ?
Thank You..
Based on your requirement, you need to use return_url instead of notify_url. For notify_url, it's used for receiving message in system back end and you maybe can't receive it immediately after payment is done. refer to https://developer.paypal.com/docs/classic/ipn/integration-guide/IPNPDTAnAlternativetoIPN/

force singleordefault to execute

Can anyone tell me why the following code does not work in an api controller (MVC4)? I get an error saying that the "Cannot access a disposed object". I found that in other cases there should be a call to ToList() so that it forces the query to be executed. But in my case, I'm using SingleOrDefault(), isn't this executed on the database right away?
public HttpResponseMessage GetPurchaseOrder(int POId)
{
PurchaseOrder po;
HttpResponseMessage resp;
using (PMDataDataContext database = new PMDataDataContext())
{
po = database.PurchaseOrders.SingleOrDefault(x => x.POId == POId);
if (po == null)
{
var message = string.Format("id = {0} not found", POId);
HttpError err = new HttpError(message);
resp = Request.CreateResponse(HttpStatusCode.NotFound, err);
}
else
{
resp = Request.CreateResponse(HttpStatusCode.OK, po);
}
}
return resp;
}
Yes, but if you have any lazy-loaded properties in PurchaseOrder, when Web API tries to serialize the object, EF will try to fetch the data from the database and for this the context will be needed but it will not be available.
Try it so that the context to database gets disposed right after the query. SingleOrDefault should send the query to the database immediately.
public HttpResponseMessage GetPurchaseOrder(int POId)
{
PurchaseOrder po;
HttpResponseMessage resp;
using (PMDataDataContext database = new PMDataDataContext())
{
po = database.PurchaseOrders.SingleOrDefault(x => x.POId == POId);
}
if (po == null)
{
var message = string.Format("id = {0} not found", POId);
HttpError err = new HttpError(message);
resp = Request.CreateResponse(HttpStatusCode.NotFound, err);
}
else
{
resp = Request.CreateResponse(HttpStatusCode.OK, po);
}
return resp;
}
Badri led me to solve my problem. When I placed a breakpoint in my code and followed in debug mode, it seemed that one of the associated objects needed the context to be fetched. The property PurchaseOrder.Item.ItemCategory was giving an ObjectDisposedException, when I was looking at the related properties.
I solved it by placing database.DeferredLoadingEnabled = false right before fetching the po using the SingleOrDefault call.

Mvc4 WepApi Empty Response when non 200

When an Action is called and throws a specific exception, I use an ExceptionFilterAttribute that translate the error into a different response as HttpStatusCode.BadRequest. This has been working locally, but we pushed it to a server and now when I get the BadRequest I do not get any information in the reponse. What am I missing?
public override void OnException(HttpActionExecutedContext actionExecutedContext)
{
MyException ex = actionExecutedContext.Exception as MyException;
if (ex == null)
{
base.OnException(actionExecutedContext);
return;
}
IEnumerable<InfoItem> items = ex.Items.Select(i => new InfoItem
{
Property = i.PropertyName,
Message = i.ToString()
});
actionExecutedContext.Result = new HttpResponseMessage<IEnumerable<InfoItem>>(items, HttpStatusCode.BadRequest);
}
Edit: When I hit the service locally the body is included. It seems the problem is when hitting the service from a remote machine.
Try this:
GlobalConfiguration.Configuration.IncludeErrorDetailPolicy =
IncludeErrorDetailPolicy.Always