Setting Authorization Header to .Net Web Service Client - c#

I know this has been asked a hundred times before, but I just can't get this working. I have a .Net web service client that needs to connect to an external web service that does not return 401 challenge response. I have to send the authentication header on the first call. I have overridden the GetWebRequest method of the generated proxy class by creating a partial class in another file. I have also added the method to the generated file to see if that makes a difference, but the code just does not get called. This was originally a .Net 3.5 Web Service Project created in VS 2013, but I have tried changing the target framework to 4.0, 4.5 e.t.c. and that does not have any effect.
The code I am using:
[System.Web.Services.WebServiceBindingAttribute(Name = "WSLDSD03_v1_webService_ValidationTicketCreation_Binder", Namespace = "http://llvap002d/WSLDSD03.v1.webService:ValidationTicketCreation")]
public partial class WSLDSD03_v1_webService_ValidationTicketCreation_Binder : System.Web.Services.Protocols.SoapHttpClientProtocol
{
protected override WebRequest GetWebRequest(Uri uri)
{
var request = base.GetWebRequest(uri);
string WSUID = ConfigurationManager.AppSettings["WSUID"];
string WSPWD = ConfigurationManager.AppSettings["WSPWD"];
string encoded = Convert.ToBase64String(System.Text.Encoding.ASCII.GetBytes(WSUID + ":" + WSPWD));
request.Headers.Add("Authorization", "Basic " + encoded);
return request;
}
}
Update: I have since found that after a clean solution and rebuild the method does in fact get called if I move it into the generated class. It is the partial class in a separate file that appears to be the problem.

It turned out to be a simple coding error. I failed to notice that the namespace in the generated proxy file was like MyProject.WebReference, but in my separate file I used the main project namespace.

Related

HttpRequest.UrlReferrer does not appear to exist

I have a web application which uses MVC4, but now realised it really should be a Web API and as such I'm moving over to a ASP.NET 4.5.2 web API 2 project.
The problem is, where I was using Request.ServerVariables[] in my MVC project I have been advised that it's not the 'correct' way in a Web API, as such, I should be using Request.RequestUrl
The example on the MSDN is simply
Uri MyUrl = Request.UrlReferrer; //kaboom for me
Response.Write("Referrer URL Port: " + Server.HtmlEncode(MyUrl.Port.ToString()) + "<br>");
Response.Write("Referrer URL Protocol: " + Server.HtmlEncode(MyUrl.Scheme) + "<br>");
The issue is, despite referencing System.Web there is no property for Request are UrlReferrer - the only properties are Content, Headers, Method, Properties, RequestUri and Version.
Why can't I use Request.UrlReferrer as per the MSDN example?
I suspect you just need to get the current request in a different way, due to being in a static method rather than in a context where you can refer to a Request instance property:
var request = HttpContext.Current;
var referrer = request.UrlReferrer;
...

Using JSON and HTTP Request in C#

I'm currently developing an Android app and I'm using Connect Android to MS SQL Server Tutorial to link my MSSQL server to the code.
And the first part is good though the second part is using a third party program to code which I don't want to. I want to write the whole code in C# (I'm using Xamarin).
I found out Json.NET / Json.NET for Xamarin website.
Though how am I supposed to use the HTTPUtils and requests in C# ? An example would be great.
Also, I have kind of a newbie question, I'm trying to get to the root of the code I sent, the .aspx file, and I don't quite understand where the web method is, I am used to a seperate .asmx file containing [Web Method]s that define them and then I can use them freely by creating a web reference on an .aspx file, so, where is the web method in the code I sent ?
public static String getJsonData(String webServiceName,String parameter)
{
try
{
String urlFinal=SERVICE_URI+"/"+webServiceName+"?parameter=";
HttpPost postMethod = new HttpPost(urlFinal.trim()+""+URLEncoder.encode(parameter,"UTF-8"));
postMethod.setHeader("Accept", "application/json");
postMethod.setHeader("Content-type", "application/json");
HttpClient hc = new DefaultHttpClient();
HttpResponse response = hc.execute(postMethod);
Log.i("response", ""+response.toString());
HttpEntity entity = response.getEntity();
String responseText = EntityUtils.toString(entity);
string=responseText;
Log.i("Output", ""+responseText);
}
catch (Exception e) {
// TODO: handle exception
}
return string;
}

how to modify http header of request; web reference in C#

I'm creating a .NET application that uses a web service. I need set the connection http header to "closed" in the request to that web service. I've been Googling this for a day but have not been able to get anything to work.
My best effort is the code below, which attempts to override the GetWebRequest method to add the header. This appears to fail - I place a breakpoint in it, and when I run my application, the breakpoint is never hit and the connection header does not appear to be set (I'm evaluating this not by viewing the http header but by the behavior of the system handling the web request).
Some information: when I added the web reference, using Visual Studio, I right-clicked on the project in the solution explorer, chose "Add Service Reference", "Advanced", then "Add Web Reference".
namespace System.Net
{
public class MyHttpProtocol : SoapHttpClientProtocol
{
protected override WebRequest GetWebRequest(Uri uri)
{
HttpWebRequest webRequest = (HttpWebRequest)base.GetWebRequest(uri);
webRequest.Headers.Add("connection", "closed");
return webRequest;
}
}
}
You need to use an IClientMessageInspector to alter the request as it's being constructed. This question is very similar and should give you the answer.
Many things in WCF involve creating behaviours and specifying them in the web config to override certain aspects of the process, which can be a bit fiddly but is very powerful. You can add your request in there.
Edit to address your comment, does your code look like this?
public object BeforeSendRequest(
ref System.ServiceModel.Channels.Message request,
System.ServiceModel.IClientChannel channel)
{
var httpRequestMessage = new HttpRequestMessageProperty();
httpRequestMessage.Headers.Add("connection", "closed");
request.Properties.Add(
HttpRequestMessageProperty.Name, httpRequestMessage);
return null;
}

How to create an otrs ticket using a soap request

The lack of documentation on this subject coupled with the fact that I'm struggling with a learning curve on all fronts and making me really confused about where to start. I need to get this done using C# if possible. I apologize for the vagueness of this question, but I'm really lost. I would love links to comprehensive guides/references.
In my efforts to get this done, I've run into the following problems/questions:
I've created a web service using the otrs gui, with the operation CreateTicket, but requests via C# to my chosen namespace are returning 404 (not found). When I try to add a service reference or web reference with that namespace, I get the same error. However, when I plug that namespace into my browser as the url, it displays "customer.pl".
Can I send a soap request without adding the web service as a service reference in visual studio? Given the previous problem I'm having I can't do it that way. Would I just build the soap request string and write it to the web request's data stream with http://domain/rpc.pl as the uri?
If the answer to the previous question is yes... When trying the below code segment I get an internal server error (500) on the last line. However the header looks like a SOAP header which confuses me because I wouldn't have thought it got that far.
var document = new StringBuilder();
document.Append("<UserLogin>some user login</UserLogin>");
document.Append("<Password>some password</Password> ");
document.Append("<Ticket>");
document.Append("<Title>some title</Title> ");
document.Append("<CustomerUser>some customer user login</CustomerUser>");
document.Append("<Queue>some queue</Queue>");
document.Append("<State>some state</State>");
document.Append("<Priority>some priority</Priority>");
document.Append("</Ticket>");
document.Append("<Article>");
document.Append("<Subject>some subject</Subject>");
document.Append("<Body>some body</Body>");
document.Append("<ContentType>text/plain; charset=utf8</ContentType>");
document.Append("</Article>");
//var uri = new Uri("http://domain/injest");
var uri = new Uri("http://domain/rpc.pl");
var httpWebReq = (HttpWebRequest)WebRequest.Create(uri);
var bytePostData = Encoding.UTF8.GetBytes(document.ToString());
httpWebReq.Timeout = 5 * 1000;
httpWebReq.Method = "POST";
httpWebReq.ContentLength = bytePostData.Length;
httpWebReq.ContentType = "text/xml;charset=utf-8";
//httpWebReq.TransferEncoding=
//httpWebReq.ContentType = "application/xml";
//httpWebReq.Accept = "application/xml";
var dataStream = httpWebReq.GetRequestStream();
dataStream.Write(bytePostData, 0, bytePostData.Length);
dataStream.Close();
var httpWebResponse = (HttpWebResponse)httpWebReq.GetResponse();
Even if all you can offer is where to start, it would help me to know how to proceed, as I'm stumped.
You're using the rpc.pl endpoint which is part of the 'old' RPC-style interface.
You mention you added the web service via the GUI which means you're using the 'new' Generic Interface, which is indeed much easier from .Net.
The address of the endpoint is /otrs/nph-genericinterface.pl/Webservice/GenericTicketConnector or whatever you have called the web service in the admin section.

How do I change the URL of a SoapHttoClientProtocol object?

I received some code from a client containg a wsdl.exe generated SoapHttpClientProtocol sub-class for us to access. I altered the code as follows:
public WebService(string url, bool useDefaultCredentials)
{
this.Url = url;
this.UseDefaultCredentials = useDefaultCredentials;
}
The client changed the URL for the web-service so we changed the config to match, unfortunately it still appears to be hitting the old URL.
The code contains several attributes referencing the old web service. Specifically a WebServiceBindingAttribute with a Namespace parameter set to the old .asmx file and a SoapDocumentMethodAttribute with the Action parameter set to the old URL and the RequestNamespace parameter set to the old .asmx file. Could these be the problem?
Update from the client: It looks like in addition to changing the location of the webservice, they also changed the Namespaces of the SOAP methods which broke the auto-generated [SoapDocumentMethod] attribute.

Categories