converting a asp.net mvc to a razor page - asp.net

I have a asp.net web app that calls a controller action with the following code:
$(function () {
$("#barcode").on("change", function (e) {
// get the current value
var barcode = $('#barcode').val();
// if there's no text, ignore the event
if (!barcode) {
return;
}
// clear the textbox
$("#barcode").val("");
// var holdit = $('#textArea1').val();
$('#textArea1').val($('#textArea1').val() +' '+ barcode);
// post the data using AJAX
$.post('#Url.Action("scanned", "receiveScan")?barcode=' + barcode);
});
})
Controller:
[Produces("application/json")]
[Route("api/receiveScan")]
public class receiveScanController : Controller
{
private static readonly HttpClient client = new HttpClient();
public ActionResult scanned(string barcode)
{
var test = barcode;
receiveScanModel newScan = new receiveScanModel();
newScan.Barcode = barcode;
newScan.companyNo = 1;
string jsonScan = JsonConvert.SerializeObject(newScan, Formatting.Indented);
var httpWebRequest = (HttpWebRequest)WebRequest.Create("http://notarealservicehere.azurewebsites.net//api/receivescan");
httpWebRequest.ContentType = "application/json";
httpWebRequest.Method = "POST";
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
streamWriter.Write(jsonScan);
}
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
var result = streamReader.ReadToEnd();
}
return Ok();
Trying to convert to my first Razor page, everything works with the exception (obviously) of the $.post part...
Where would this go?
It is a asp.net core app with razor pages

Use a handler for example
on your cs file
public IActionResult OnPostBarcode(string barcode)
on your js
var uri = "myPage/?handler=Barcode"
$.post( uri ,{barcode:barcode}, function( data ) {
console.log(data)
});

Related

IActionSelectorDecisionTreeProvider namespace could not be found in .Net 5

I want to create an extension method of #Html.Action But Showing Error for IActionSelectorDecisionTreeProvider could not load namespace
var actionSelector = GetServiceOrFail<IActionSelectorDecisionTreeProvider>(currentHttpContext);
Error Screen Short
I have installed all dependencies of dot.net 5 like
using System;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Html;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Infrastructure;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.AspNetCore.Routing;
But No Luck.
Working Code In Dot Net 5
public static class HtmlHelperViewExtensions
{
public static IHtmlContent RenderAction(this IHtmlHelper helper, string action, object parameters = null)
{
var controller = (string)helper.ViewContext.RouteData.Values["controller"];
return RenderAction(helper, action, controller, parameters);
}
public static IHtmlContent RenderAction(this IHtmlHelper helper, string action, string controller, object parameters = null)
{
var area = (string)helper.ViewContext.RouteData.Values["area"];
return RenderAction(helper, action, controller, area, parameters);
}
public static IHtmlContent RenderAction(this IHtmlHelper helper, string action, string controller, string area, object parameters = null)
{
if (action == null)
throw new ArgumentNullException("action");
if (controller == null)
throw new ArgumentNullException("controller");
//if (area == null)
// throw new ArgumentNullException("area");
var task = RenderActionAsync(helper, action, controller, area, parameters);
return task.Result;
}
private static async Task<IHtmlContent> RenderActionAsync(this IHtmlHelper helper, string action, string controller, string area, object parameters = null)
{
// fetching required services for invocation
var currentHttpContext = helper.ViewContext?.HttpContext;
var httpContextFactory = GetServiceOrFail<IHttpContextFactory>(currentHttpContext);
var actionInvokerFactory = GetServiceOrFail<IActionInvokerFactory>(currentHttpContext);
var actionSelector = GetServiceOrFail<IActionDescriptorCollectionProvider>(currentHttpContext);
// creating new action invocation context
var routeData = new RouteData();
var routeParams = new RouteValueDictionary(parameters ?? new { });
var routeValues = new RouteValueDictionary(new { area = area, controller = controller, action = action });
var newHttpContext = httpContextFactory.Create(currentHttpContext.Features);
newHttpContext.Response.Body = new MemoryStream();
foreach (var router in helper.ViewContext.RouteData.Routers)
routeData.PushState(router, null, null);
routeData.PushState(null, routeValues, null);
routeData.PushState(null, routeParams, null);
var actionDescriptor = actionSelector.ActionDescriptors.Items.Where(i => i.RouteValues["controller"] == controller && i.RouteValues["action"] == action).First();
var actionContext = new ActionContext(newHttpContext, routeData, actionDescriptor);
// invoke action and retreive the response body
var invoker = actionInvokerFactory.CreateInvoker(actionContext);
string content = null;
await invoker.InvokeAsync().ContinueWith(task => {
if (task.IsFaulted)
{
content = task.Exception.Message;
}
else if (task.IsCompleted)
{
newHttpContext.Response.Body.Position = 0;
using (var reader = new StreamReader(newHttpContext.Response.Body))
content = reader.ReadToEnd();
}
});
return new HtmlString(content);
}
private static TService GetServiceOrFail<TService>(HttpContext httpContext)
{
if (httpContext == null)
throw new ArgumentNullException(nameof(httpContext));
var service = httpContext.RequestServices.GetService(typeof(TService));
if (service == null)
throw new InvalidOperationException($"Could not locate service: {nameof(TService)}");
return (TService)service;
}
}

HttpClient return json response on localhost when application live on server it's return html

I'm calling API using HttpClient below code running fine on localhost but when it's live on server it's return html response.
here is the code i'm using
public async Task<ActionResult> getPost()
{
string url = "https://www.instagram.com/p/Bg9DwFYHARK/?__a=1";
HttpClient _client = new HttpClient();
var Response = await _client.GetAsync(url);
if (Response.IsSuccessStatusCode)
{
var Result = Response.Content.ReadAsStringAsync().Result;
//here in **Result** i've received html instead of json or when i received html instead
of json got error on DeserializeObject.
var Jsonresult = JsonConvert.DeserializeObject<post>(Result);
return Json(new { isValid = false, error = "post found", obj = Jsonresult }, JsonRequestBehavior.AllowGet);
}
else
{
return Json(new { isValid = false, error = "post not found" }, JsonRequestBehavior.AllowGet);
}
}
This method response is JSON.
string uri = "https://www.instagram.com/p/Bg9DwFYHARK/?__a=1";
private static async Task<ActionResult> getPost(string uri)
{
var webRequest = WebRequest.Create(uri) as HttpWebRequest;
if (webRequest == null)
{
return;
}
webRequest.ContentType = "application/json";
webRequest.UserAgent = "Nothing";
using (var s = webRequest.GetResponse().GetResponseStream())
{
using (var sr = new StreamReader(s))
{
// var contributorsAsJson = sr.ReadToEnd();
var contributors = JsonConvert.DeserializeObject<Create a list >(contributorsAsJson);
// contributors.ForEach(Console.WriteLine);
return contributors;
}
}
}
I get out put is:
{"graphql":{"shortcode_media":{"__typename":"GraphImage","id":"1746568728937235530","shortcode":"Bg9DwFYHARK","dimensions":{"height":1080,"width":1080},"gating_info":null,"fact_check_overall_rating":null,"fact_check_information":null,"sensitivity_friction_info":null,"media_overlay_info":null,"media_preview":"ACoqytpjBOM+tQs6t07nvxwOn4889q2TDuGKzrfT2kkKtkBDz7j2PT0/OlpuUm7cvQqrbSS/cBb6D/IqI8DHfvXZiVI12qpBA+7xwPr0/WueMXm3LMBx94jryf0PrSTdwaVrlSKMsKd5ZrYji7n8B/8AWp3k+wp3ILSKT0FBkW2YM/AcEZ9xz+o4+uBVgyBSB26VDcWgnYFuVUEbfr3B9Qarl0HcRrgqQWVlX5snjIBxgsOw9fTFR2xEu+QdHbj6DgH8earPayvuUuXXHTGC2OgZv5461pQRGKNY+PlABx69/wBamKvuVJ9iMgikqwy4qPZSasJambblpm3dlP5n69x/9atgetZ1h/qV/H+ZrQHQfhWl7tk2JqY7bQT6UtRvTAN2aZUSnn8am2L6D8qdk9xbH//Z","display_url":"https://instagram.fcok6-1.fna.fbcdn.net/v/t51.2885-15/e35/29400587_173904939930435_4131401846013034496_n.jpg?_nc_ht=instagram.fcok6-1.fna.fbcdn.net&_nc_cat=103&_nc_ohc=cgtRDraKPGoAX_a9AvI&oh=fc8640215bbe4a5003bbaf694113951c&oe=5F2FFE5A","display_resources":[{"src":"https://instagram.fcok6-1.fna.fbcdn.net/v/t51.2885-15/sh0.08/e35/s640x640/29400587_173904939930435_4131401846013034496_n.jpg?_nc_ht=instagram.fcok6-1.fna.fbcdn.net&_nc_cat=103&_nc_ohc=cgtRDraKPGoAX_a9AvI&oh=e971123fdc4eb19abe4a96b35195dd9f&oe=5F30CFBD","config_width":640,"config_height":640},{"src":"https://instagram.fcok6-1.fna.fbcdn.net/v/t51.2885-15/sh0.08/e35/s750x750/29400587_173904939930435_4131401846013034496_n.jpg?_nc_ht=instagram.fcok6-1.fna.fbcdn.net&_nc_cat=103&_nc_ohc=cgtRDraKPGoAX_a9AvI&oh=33fe7c336ecff4205e161452adfc7ecf&oe=5F31703D","config_width":750,"config_height":750},{"src":"https://instagram.fcok6-1.fna.fbcdn.net/v/t51.2885-15/e35/29400587_173904939930435_4131401846013034496_n.jpg?_nc_ht=instagram.fcok6-1.fna.fbcdn.net&_nc_cat=103&_nc_ohc=cgtRDraKPGoAX_a9AvI&oh=fc8640215bbe4a5003bbaf694113951c&oe=5F2FFE5A","config_width":1080,"config_height":1080}],"accessibility_caption":"Photo by Ateeq Khalil in Salt N Pepper Liberty. Image may contain: 1 person","is_video":false,"tracking_token":"eyJ2ZXJzaW9uIjo1LCJwYXlsb2FkIjp7ImlzX2FuYWx5dGljc190cmFja2VkIjp0cnVlLCJ1dWlkIjoiZWQ2ZjUxNTZjMjc5NDU5MzlmMmQ1MTQzZDBhZmIyYjYxNzQ2NTY4NzI4OTM3MjM1NTMwIn0sInNpZ25hdHVyZSI6IiJ9","edge_media_to_tagged_user":{"edges":[]},"edge_media_to_caption":{"edges":[]},"caption_is_edited":false,"has_ranked_comments":false,"edge_media_to_parent_comment":{"count":0,"page_info":{"has_next_page":false,"end_cursor":null},"edges":[]},"edge_media_to_hoisted_comment":{"edges":[]},"edge_media_preview_comment":{"count":0,"edges":[]},"comments_disabled":false,"commenting_disabled_for_viewer":false,"taken_at_timestamp":1522427239,"edge_media_preview_like":{"count":19,"edges":[]},"edge_media_to_sponsor_user":{"edges":[]},"location":{"id":"1730525857251432","has_public_page":true,"name":"Salt N Pepper Liberty","slug":"salt-n-pepper-liberty","address_json":"{\"street_address\": \"48 Commercial Zone Liberty Market, Gulberg III\\u060c\", \"zip_code\": \"\", \"city_name\": \"Lahore, Pakistan\", \"region_name\": \"\", \"country_code\": \"PK\", \"exact_city_match\": false, \"exact_region_match\": false, \"exact_country_match\": false}"},"viewer_has_liked":false,"viewer_has_saved":false,"viewer_has_saved_to_collection":false,"viewer_in_photo_of_you":false,"viewer_can_reshare":true,"owner":{"id":"5394358177","is_verified":false,"profile_pic_url":"https://instagram.fcok6-1.fna.fbcdn.net/v/t51.2885-19/s150x150/29402856_149619235868663_6235876322871083008_n.jpg?_nc_ht=instagram.fcok6-1.fna.fbcdn.net&_nc_ohc=gSyry9Wj5UkAX_bQlzD&oh=bdc6a6b82077c8e461aedbaffa7e49db&oe=5F32308B","username":"ateeq.khalil","blocked_by_viewer":false,"restricted_by_viewer":null,"followed_by_viewer":false,"full_name":"Ateeq Khalil","has_blocked_viewer":false,"is_private":false,"is_unpublished":false,"requested_by_viewer":false,"edge_owner_to_timeline_media":{"count":7},"edge_followed_by":{"count":175}},"is_ad":false,"edge_web_media_to_related_media":{"edges":[]},"edge_related_profiles":{"edges":[]}}}}

How to send file with HttpClient post in xamarin forms

I want to send file through post request using httpclient
this what i tried but file didn't sent , when i tried in postman it works fine
string Url = $"http://ataprojects.net/test/products.php?request_type=add&company_name={BaseService.Company}&name={product.name}&barcode={product.barcode}&buy_price={product.buy_price}&sell_price={product.sell_price}";
try
{
using (HttpClient client = new HttpClient())
{
var content = new MultipartFormDataContent();
content.Headers.ContentType.MediaType = "multipart/form-data";
content.Add(new StreamContent(product._mediaFile.GetStream()),
"image",
product.image);
var response = client.PostAsync(Url, content).Result;
response.EnsureSuccessStatusCode();
if (response.IsSuccessStatusCode)
{
var contentdata = await response.Content.ReadAsStringAsync();
var Items = JsonConvert.DeserializeObject<AddProductReturnModel>(contentdata);
return Items;
}
else
{
return null;
}
}
}
what's the problem ?
Try This Code
var content = new MultipartFormDataContent();
content.Add(new StreamContent(product._mediaFile.GetStream()),
"\"file\"",
$"\"{product._mediaFile.Path}\"");

Is there a utility to serialise an object as HTTP content type "application/x-www-form-urlencoded"?

I've never had to do this before, because it's always only been an actual form that I've posted as that content type, but recently I had to post three variables like that, and I resorted to a sordid concatenation with & and =:
var content = new StringContent("grant_type=password&username=" + username + "&password=" + password.ToClearString(), Encoding.UTF8,
"application/x-www-form-urlencoded");
I'm sure there must be a utility method that would do that, and do it better, with any necessary encoding. What would that be?
If this is a POCO and just using the Newtonsoft library, you can use this as well:
public static class FormUrlEncodedContentExtension
{
public static FormUrlEncodedContent ToFormUrlEncodedContent(this object obj)
{
var json = Newtonsoft.Json.JsonConvert.SerializeObject(obj);
var keyValues = JsonConvert.DeserializeObject<Dictionary<string, string>>(json);
var content = new FormUrlEncodedContent(keyValues);
return content;
}
}
And a sample usage would be:
var myObject = new MyObject {Grant_Type = "TypeA", Username = "Hello", Password = "World"};
var request = new HttpRequestMessage(HttpMethod.Post, "/path/to/post/to")
{
Content = myObject.ToFormUrlEncodedContent()
};
var client = new HttpClient {BaseAddress = new Uri("http://www.mywebsite.com")};
var response = await client.SendAsync(request);
Use reflection to get the property names and values and then use them to create a System.Net.Http.FormUrlEncodedContent
public static class FormUrlEncodedContentExtension {
public static FormUrlEncodedContent ToFormUrlEncodedContent(this object obj) {
var nameValueCollection = obj.GetType()
.GetProperties()
.ToDictionary(p => p.Name, p => (p.GetValue(obj) ?? "").ToString());
var content = new FormUrlEncodedContent(nameValueCollection);
return content;
}
}
From there it is a simple matter of calling the extension method on an object to convert it to a FormUrlEncodedContent
var model = new MyModel {
grant_type = "...",
username = "...",
password = "..."
};
var content = model.ToFormUrlEncodedContent();
You should be able to use string interpolation for that. Something like:
var content = new StringContent($"grant_type=password&username={username}&password={password}", Encoding.UTF8, "application/x-www-form-urlencoded");
Or wrap this inside a helper/factory method:
public static class StringContentFactory
{
public static StringContent Build(string username, string password)
{
return new StringContent($"grant_type=password&username={username}&password={password}", Encoding.UTF8, "application/x-www-form-urlencoded");
}
}

Accessing the returned XML from an API call

I have the following action method to perform an API call:-
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(Rack rack, FormCollection formValues)
{
if (ModelState.IsValid) {
using (var client = new WebClient())
{
var query = HttpUtility.ParseQueryString(string.Empty);
foreach (string key in formValues)
{
query[key] = this.Request.Form[key];
}
query["username"] = "testuser";
query["password"] = ///.....
query["assetType"] = "Rack";
query["operation"] = "AddAsset";
var url = new UriBuilder("http://win-spdev:8400/servlets/AssetServlet");
url.Query = query.ToString();
try
{
string xml = client.DownloadString(url.ToString());
}
The return XML from the API call looks as follow:-
<operation>
<operationstatus>Failure</operationstatus>
<message>Rack already exists.Unable to add</message>
</operation>
but how i can reach the message and operationstaus and according to them to display an appropriate message . i use to serialize the returned Json such as , but i am not sure how to do so for the xML:-
var serializer = new JavaScriptSerializer();
var myObject = serializer.Deserialize<newprocess>(json);
string activityid = myObject.activityId;
Just load it into an XmlDocument.
Untested and from the top of my head:
var xmlDoc = new XmlDocument();
xmlDoc.LoadXml(theXML);
var status = xmlDoc.SelectSingleNode("/operation/operationstatus").InnerText;
var message = xmlDoc.SelectSingleNode("/operation/message").InnerText;
If you using ASP.NET mvc, I believe you can use HttpClient, instead of WebClient:
Define result class:
public class operation
{
public string operationstatus{get;set;}
public string message{get;set;}
}
And then use it for automatic deserilization:
var client = new HttpClient();
var result = client.PostAsync(url,
new FormUrlEncodedContent(new Dictionary<string, string>{
{"username","testuser"},
{"assetType","Rack"}}))
.Result.Content
.ReadAsAsync<operation>().Result;

Resources