Call WebAPI to .NET Framework from .NET Core - c#

I have backend project on ASP .NET Core. I write a web api into this project. Also, I have UI project on .NET Framework. I want to call web apis from .NET Frameowork and use it. What's best approches is it?

Seems you are trying to call Web API from your Windows Form application.
You can try this way:
On your Windows from Button Click event you can write this code snippet
private void Button2_Click(object sender, EventArgs e)
{
HttpClient _httpClient = new HttpClient();
string uri = "http://localhost:11951/api/MsAgent/GetMSAgentByAlias?alias=TestParam";
var _http_response = _httpClient.GetAsync(uri);
_http_response.Wait();
var _read_response = _http_response.Result.Content.ReadAsStringAsync();
_read_response.Wait();
if (_read_response.Result.Contains("No Data Found!"))
{
// Your Logic what you would like to do when no response
}
var data = JsonConvert.DeserializeObject<MSAgentViewModel>(_read_response.Result);
//Do what you wants to do with your API response
//Can Bind Data With From Property
}
This is one way, you can make the API Service Class in diffrent class its up to you. Lot of best practice out there. Let me know if you require more help on this.

Related

using ControllerContext.RequestContext in a web api controller

I am try to integrate SagePayMvc.dll into a ASP.NET Web API project which requires ControllerContext.RequestContext to be passed in order to form the Notification Url.
Currently I am experiencing some difficulties in achieving this, I need to pass the ControllerContext.RequestContext from this web api controller:
public class PaymentStartController : ApiController
{
private PaymentRepository paymentRepository = new PaymentRepository();
private SagePayHelper sagePayHelper = new SagePayHelper();
public Order MakePaymentInitial(Payment payment)
{
Order order = new Order();
order = sagePayHelper.MakePayment(payment, context);
paymentRepository.InsertVendorTXCode(order.VendorTxCode);
paymentRepository.InsertInitialPaymentDetails(order, payment);
return order;
}
}
I have tried to add a public ControllerContext controllerContext = new ControllerContext() below the SagePayHelper instantiation and then subsequently added var context = controllerContext.RequestContext, the problem with this none of the methods inside RequestContext are instantiated either so when SagePayMvc arrives at the point of building the Notification Url which is done inside an IUrlResolver interface an error is thrown.
Is there a way of mocking up ControllerContext.RequestContext, I have previously used RhinoMocks or would it be more prudent to revert to the way I previously implemented SagePayMvc down in the forms project (the forms project is an MVC 4 application that serializes and sends the form data to the web api).
Any advise would be much appreciated.
ASP.NET Web API uses completely different runtime components from ASP.NET MVC for representing the context and request/response messages. It looks like the API you are using is heavily tied to ASP.NET MVC, which makes it really hard to reuse in ASP.NET Web API unless you initialize the ASP.NET MVC content doing manual mappings. I think it would be easier for you to just use ASP.NET MVC for invoking that method expecting the MVC context.

View engines for non-mvc web application

I'd like to achieve the MVC View Engine behavior in an web forms application. To register a mobile channel in MVC I normally would do something like this
public static List<string> UaSurfpads = new List<string>()
{
"iPad",
"MicrosoftRt",
"PlayBook"
};
protected void Application_Start(object sender, EventArgs e)
{
// register surfpads
foreach (string device in UaSurfpads)
{
DisplayModeProvider.Instance.Modes.Insert(0, new DefaultDisplayMode("mobile")
{
ContextCondition = (context => context != null && context.GetOverriddenUserAgent().IndexOf(device, StringComparison.OrdinalIgnoreCase) >= 0)
});
}
// ...
}
This will enable me to create shadow views like myView.mobile.cshtml.
Is there any similar way to work using regular web forms in asp.net?
ASP.NET WebForm also have mobile features, as well as MVC. Just read this article
Also, official MS web source for mobile development
There is nothing native live MVC to handle this. However, you can achieve this by putting some code in your app to detect and redirect. 51 degrees used this approach and created a freely available framework to do all of this. I'd recommend looking at it, or at least how they achieve their mobile implementation, and mimic it for your site.

VS 2010 Intellisense Issue

I'm working on a C# library class which is being consumed by an ASP.NET 4.0 Web Forms application. In my class, I'm trying to access the HttpRequest.Application object as described here:
http://msdn.microsoft.com/en-us/library/system.web.httprequest.applicationpath.aspx
This documentation says it is in the System.Web namespace but even when I add a reference in my library project, it is still not available to me.
The only way I can get to the ApplicationPath property is by using:
HttpContext.Current.Request.ApplicationPath;
What's going on?
ApplicationPath is not a static property on HttpRequest, which is why you have to access it using the instance HttpContext.Current.Request. If you don't want to use HttpContext.Current.Request you could always pass the HttpRequest object in to your class library from your ASP.NET web forms.
For example (from your Page_Load):
protected void Page_Load(object sender, EventArgs e)
{
var myClass = new MyClass();
myClass.MyMethod(this.Request);
}

Calling a Java Web service from silverlight throws an exception

After my previous question HERE, I found the solution (well, part of it).
Here's the code for Java part:
#WebService
public class MyWebService
{
#WebMethod
public String myMethod()
{
return "Hello World";
}
#WebMethod
public int Add(#WebParam(name="a") int a,
#WebParam(name="b") int b)
{
return a + b;
}
public static void main(String[] args)
{
String address = "http://127.0.0.1:8023/_WebServiceDemo";
Endpoint.publish(address, new MyWebService());
System.out.println("Listening: " + address);
}
}
And Here is the Silverlight part:
private void SearchResultList_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
MyWebServiceClient proxy = new MyWebServiceClient();
proxy.AddCompleted += proxy_AddCompleted;
proxy.AddAsync(2, 3);
}
void proxy_AddCompleted(object sender, AddCompletedEventArgs e)
{
txtSearch.Text = e.Result.ToString();
}
But when I run this, e.Result throws an exception.
What am I missing/ How should I solve it?
Note that this code runs perfectly in C# Console application (when it's not async). But when I run the async code, it doesn't work.
Thanks in advance.
I guess you are getting a System.ServiceModel.CommunicationException when trying to access the Java Webservice from Silverlight.
There is nothing basically wrong with your code, and it should also work with async calls in C# Console App.
The main problem is that Silverlight (as a browser plugin) enforces some security restrictions that prevent a Silverlight Application to talk to another server than the one loaded from (defined by server name and port) without further configuration. This behaviour can be configured as described here (also search for "silverlight cross-domain calls" or "silverlight cross domain policy").
This restrictions (normally) do not apply to desktop or console applications so they'll work fine with the same web service.
To make your code work you need to host the Silverlight Application inside the same "project" / website than your webservice (so I suppose, the self-hosting webservice won't work and you need to switch to Java web project where the webservice is to be hosted). As the Silverlight Application basically consists of an enclosing HTML file plus the referenced binaries, you can host it on any server, e.g. Apache Tomcat.
Hope this helps.

Passing parameters from silverlight to ASP.net

I've made a little game in silverlight that records users scores whilst they play.
I decided it would be a lot better if I could implement a leaderboard, so I created a database in mySQL to store all the high scores along with names and dates. I have created some communications to the database in ASP.net. This works and I can simply insert and get data within the code.
It's now time to link the silverlight project with the ASP.net database communications, so I can send the users name and score as variables to my ASP.net code and then it will upload it to the database. That's all I need. Surely there must be an easy way of doing this, I just can't seem to find any ways when researching.
Thanks in advance,
Lloyd
At first you need add Generic Handler to your ASP.Net project.
public class Handler1 : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
string userName = context.Request["user"];
int score = int.Parse(context.Request["score"]);
//And store it in DB
}
}
After you need call this handler from SilverLight app:
string uri = HtmlPage.Document.DocumentUri.ToString();
// Remove the web page from the current URI to get the root URI.
string rootUri = uri.Remove(uri.LastIndexOf('/'),
uri.Length - uri.LastIndexOf('/'));
string diggUrl = String.Format(rootUri + "/" + "test.ashx?user={0}&score={1}", "testuser", "234");
// Initiate Async Network call to Digg
WebClient diggService = new WebClient();
diggService.DownloadStringAsync(new Uri(diggUrl));
here i used Uri Class to send parameter to asp.net, but you can send string format only.
// this code written on Silverlight Button Click Event.
Uri myURI = new Uri(HtmlPage.Document.DocumentUri,String.Format("Report.aspx?brcd={0}&acc={1}&user={2}", Brcd, Acc, User)); HtmlPage.Window.Navigate(myURI, "_blank");
below code is written on Asp.net page_load or page init event
Brcd = Request.QueryString["brcd"];// brcd value accept here.
acc= Request.QueryString["ACC"];`
user= Request.QueryString["User"];
in above code we accept the silverlight parameter in asp.net but in [] bracket put name as it is use in silverlight page because it case sensitive.
By ASP.NET, do you mean an ASP.NET Webforms app?
If so, an ASP.NET Webforms app is a method of building a UI. What you need is an API, for your Silverlight app to use programatically. For this purpose you may want to consider building an ASP.NET Webservice instead, which provides an API over HTTP.
What do you need its to send data to web server from a Silverlight application, right?
You can:
Call Javascript functions from Silverlight and, there, do a postback
Call web services with Silverlight, but make sure its in same server which your SL application came from, or you will face some XSS issues.
An easy way to do this is to have your Silverlight code create a REST URL by encoding the information into the query string, and invoking an .aspx page on the server. The page wouldn't need to return any markup; it would just handle the back-end stuff and return.
Alternatively, you could make a web service call from Silverlight to your back end.
I prefer the latter approach. It's a little more work the first time through, but it's also more general purpose and makes for generally better code in the long run.
Although technically you could use JavaScript, I wouldn't suggest it; why go backwards in tech if you don't have to?

Categories

Resources