I need to call a web service from a .net web application, here is my code:
LoginRequest req = new LoginRequest();
LoginRequestBody reqBody = new LoginRequestBody();
reqBody.username = txtUsername.Text;
reqBody.password = txtPassword.Text;
req.Body = reqBody;
LoginResponse resp = new LoginResponse();
LoginResponseBody respBody = new LoginResponseBody();
resp.Body = respBody;
MessageBox.Show(respBody.LoginResult.ToString());
The message returned is always false, while the message from the web service (when I test directly) is returning true, what's wrong with my code?
You are not actually calling the web-service! You should not be creating a response directly - you should be asking the web-service for one, e.g.
LoginResponse response = LoginService.Login(req);
However, I don't know what your service is actually called, so the above is just a sample.
Related
The following code takes a target uri and gets its content as stream. Before the network call is made, it checks whether a proxy is required to access the target uri or not.
This works perfectly for .NET apps in full-framework (i.e. v4.8):
var targetUri = new Uri("...");
HttpClient client;
// get the system default web proxy ...
var proxyUri = WebRequest.DefaultWebProxy.GetProxy(targetUri);
// ... and check whether it should be used or not
var proxyAuthorityEqualsTargetAuthority = proxyUri?.Authority?.Equals(targetUri.Authority) == true;
var proxyRequired = !proxyAuthorityEqualsTargetAuthority;
if (proxyRequired)
{
var proxy = new WebProxy()
{
Address = proxyUri,
BypassProxyOnLocal = false,
UseDefaultCredentials = true
};
var httpClientHandler = new HttpClientHandler { Proxy = proxy };
client = new HttpClient(handler: httpClientHandler, disposeHandler: true);
}
else
{
client = new HttpClient();
}
await client.GetStreamAsync(targetUri) ...
However it does not work within a .NET Core app:
Accessing WebRequest.DefaultWebProxy.GetProxy(targetUri) will throw a PlatformNotSupportedException:
Operation is not supported on this platform.
So I tried this line instead which is supported by .NET Core as well:
// deprecated: var proxyUri = new Uri(WebRequest.DefaultWebProxy.GetProxy(targetUri).AbsoluteUri);
var proxyUri = new WebProxy().GetProxy(targetUri);
However, the returning proxyUri.Authority does always return the targetUri now (both, in .NET and .NET Core) instead of the address to the proxy server like WebRequest.DefaultWebProxy.GetProxy(targetUri) does in .NET.
This way, proxyAuthorityEqualsTargetAuthority is always true and therefore, proxyRequired is always false. Accessing the target uri directly throws a 407 (Proxy Authentication Required).
Does anyone know how to get the address of the default web proxy in .NET Core?
Okay, I don't know what I missed as I tried this weeks ago. I tried again and everything seems fine.
With CredentialCache.DefaultCredentials, this short code works with both: .NET and .NET Core.
var targetUri = new Uri("...");
var handler = new HttpClientHandler();
handler.DefaultProxyCredentials = CredentialCache.DefaultCredentials;
var client = new HttpClient(handler, disposeHandler: true);
await client.GetStreamAsync(targetUri) ...
I am trying to authenticate using auth0.net (.NET client for the Auth0 API), however, I'm getting an Auth0.Core.Exceptions.ApiException error with an HTTP status code of NotFound (404).
I'm using the following code:
var client = new AuthenticationApiClient(new Uri(Auth0Url));
var authenticationRequest = new AuthenticationRequest();
authenticationRequest.ClientId = ClientId;
authenticationRequest.Username = username;
authenticationRequest.Password = password;
authenticationRequest.Connection = "Username-Password-Authentication";
AuthenticationResponse response = null;
Task.Run(async () =>
{
response = await client.AuthenticateAsync(authenticationRequest);
}).Wait();
What is wrong here? The Management API works fine and the ClientID is correct.
Just had this problem myself.
Two things.
First make sure you are using the correct API Url.
E.g.
https://<company>.au.auth0.com/api/v2
And not
https://<company>.au.auth0.com
Second Make sure you are using the base API
E.g.
https://<company>.au.auth0.com/api/v2
And not
https://<company>.au.auth0.com/api/v2/users
I am trying to port an application from an azure mobile service to an azure web app. (the mobile service was working). I have added microsoft account authentication to the web-app, and the web app api has a MobileAppController attribute. I have a Universal windows app front end that calls the api. The app first checks if a player is in the database, if not I get a not found response. If I call the method using the following code with the MobileServiceClient I get an exception.
private async Task<HttpResponseMessage> GetAZMAsyncP(string apiext, IDictionary<string,string> param )
{
string myuri = String.Format("{0}{1}", urlbase, apiext);
//client is the MobileServiceClient that is correctly logged in
//I do not get response which is 404 not found, I get an exception "The request could not be completed, Not Found"
var response = await client.InvokeApiAsync(myuri, System.Net.Http.HttpMethod.Get, param);
return response;
}
If I call the api from an httpclient and add my own headers, which the mobile client is supposed to do for me, then I get the response as requested. Here is the code:
private async static Task<HttpResponseMessage> GetAZAsync(string apiext)
{
string completeUrl = String.Format("{0}{1}", urlbase, apiext);
// Call out to AZ
using (var http = new HttpClient())
{
// http.BaseAddress = new Uri(completeUrl);
HttpRequestMessage rq = new HttpRequestMessage()
{
RequestUri = new Uri(completeUrl),
Method = HttpMethod.Get
};
addauthheader(rq);
var response = await http.SendAsync(rq);
return response;
}
}
private static void addauthheader(HttpRequestMessage rq)
{
MobileServiceUser user = App.client.CurrentUser;
rq.Headers.Add("X-ZUMO-FEATURES", "AT,QS");
rq.Headers.Add("X-ZUMO-INSTALLATION-ID",
"ff90f37e-0c03-4c52-a343-af711752e383");
rq.Headers.Add("X-ZUMO-AUTH", user.MobileServiceAuthenticationToken);
rq.Headers.Add("Accept", "application/json");
rq.Headers.Add("User-Agent", "ZUMO/2.1");
rq.Headers.Add("User-Agent",
"(lang = Managed; os = Windows Store; os_version = --; arch = X86; version = 2.1.40707.0)");
rq.Headers.Add("X-ZUMO-VERSION",
"ZUMO/2.1(lang = Managed; os = Windows Store; os_version = --; arch = X86; version = 2.1.40707.0)");
rq.Headers.Add("ZUMO-API-VERSION", "2.0.0");
}
You can try this out as it is live (and buggy).
https://gamenote2.azurewebsites.net/api/Players?displayname=Paul Goldschmidt&teamid=arizona-diamondbacks
Should give you a 404,
https://gamenote2.azurewebsites.net/api/Players?displayname=Chase Utley&teamid=los-angeles-dodgers
should give you a chase utley object. (YOu will be asked to log into a Microsoft Account).
So my questions: 1. Can I fix the mobileclient call to get a response instead of an execption
2. Is there any good reason for me to be spending so much time on this.
If you examine the exception, you will note that the status code is in there - it's just in a property that is not serialized. Just surround your InvokeApiAsync() call with a try/catch and test for the StatusCode. It should be a lot easier than writing your own HTTP Client code for the same purpose.
Specifically, MobileServiceInvalidOperationException contains the HttpResponse of the failed request, so you can check exception.Response.StatusCode value.
I am trying to write a simple POST request to google-analytics server, here is my code :
using (var client = new System.Net.WebClient())
{
var values = new System.Collections.Specialized.NameValueCollection();
//values["v"] = "1";
//values["t"] = "event";
//values["tid"] = trackingID;
//values["cid"] = clientID;
//values["ec"] = eventCategory.ToString();
//values["ea"] = eventAction.ToString();
//values["el"] = eventAction.ToString();
var endpointAddress = "http://www.google-analytics.com/collect";
var response = client.UploadValues(endpointAddress, values);
var responseString = System.Text.Encoding.Default.GetString(response);
}
This code works fine in a console application, but not on a website application (hosted on IIS or run on Visual Studio 2013) or in a WCF (likewise).
I checked using
WindowsIdentity.GetCurrent()
in both the site, the WCF service and the application, everytime the DOMAIN and USERNAME are my own, so I don't think that is the problem. I have tried using .NET impersonation without success.
I've tried setting the application pool identity to my user, ApplicationPoolIdentity or NetworkService, without success.
I've also tried changing the authentication mode to AnonymousUser or Windows Authentication. I've tried changing the physical access path, without success.
I'm at work behind a proxy, at home I've tried it and it worked well.
Does anyone has an idea as to why it doesn't work ?
Try supplying the proxy details when making the request. Assuming you are behind a proxy.
using (var client = new System.Net.WebClient())
{
WebProxy proxy = new WebProxy("localproxyIP:8080", true);
proxy.Credentials = new NetworkCredential("domain\\user", "password");
WebRequest.DefaultWebProxy = proxy;
client.Proxy = proxy;
var values = new System.Collections.Specialized.NameValueCollection();
//values["v"] = "1";
//values["t"] = "event";
//values["tid"] = trackingID;
//values["cid"] = clientID;
//values["ec"] = eventCategory.ToString();
//values["ea"] = eventAction.ToString();
//values["el"] = eventAction.ToString();
var endpointAddress = "http://www.google-analytics.com/collect";
var response = client.UploadValues(endpointAddress, values);
var responseString = System.Text.Encoding.Default.GetString(response);
}
I have a web service in SAP and I have to make a C# client to te web service. I create the client but I receive an error from C#. Error is this :
Object reference not set to an instance of an object.
My source for client is this:
Uri uri = new Uri("http://address");
var address = new EndpointAddress(uri, EndpointIdentity.CreateSpnIdentity("teste"));
ServiceReference2.ZWS_PEP_ENVIO_MRZClient wsclient = new ServiceReference2.ZWS_PEP_ENVIO_MRZClient();
// wsclient.Endpoint.Binding.Scheme;
wsclient.ClientCredentials.UserName.UserName = "user_name";
wsclient.ClientCredentials.UserName.Password = "password";
wsclient.Endpoint.Address = address;
wsclient.Open();
ServiceReference2.ZwsPepEnvioMrz request = new ServiceReference2.ZwsPepEnvioMrz();
request.Descricao = descricaoField;
request.Mrz1 = mrz1Field;
request.Mrz2 = mrz2Field;
request.Numeroprocesso = numeroprocessoField;
request.Sn = snField;
request.Statusdatapreparation = statusdatapreparationField;
request.Versaodocumento = versaodocumentoField;
wsclient.ZwsPepEnvioMrz(request);
ServiceReference2.ZwsPepEnvioMrzResponse1 response = new ServiceReference2.ZwsPepEnvioMrzResponse1();
Resultado = response.ZwsPepEnvioMrzResponse.ToString();
textBox1.Text = Resultado;
wsclient.Close();
And the program terminates at
Resultado= response.ZwsPepEnvioMrzResponse.ToString()
Any ideas why?
this won't work:
wsclient.ZwsPepEnvioMrz(request);
ServiceReference2.ZwsPepEnvioMrzResponse1 response = new ServiceReference2.ZwsPepEnvioMrzResponse1();
you can't create a new response object yourself and expect it to contain any data. The response object should be the result from your web service call. I can't check this as the types are specific to your web service, but if the ws method ZwsPepEnviroMrz returns an object of type ServiceReference2.ZwsPepEnvioMrzResponse1 you should try this:
ServiceReference2.ZwsPepEnvioMrzResponse1 response = wsclient.ZwsPepEnvioMrz(request);
now the response variable should contain some data and this
Resultado = response.ZwsPepEnvioMrzResponse.ToString();
should work.