Click here to Skip to main content
15,893,508 members

Calling a WCF service with HttpWebRequest having custom authentication

Umais ASGHAR asked:

Open original thread
There is an answered question here but my case is a little different.

1) it's not a REST service
2) it has custom username-password validation

what I need is to call the service using HttpWebRequest "POST" method with JSON request and response format; this is what I have so far...

C#
public class Service : IService
{
    public string SayHello(string name)
    {
        return String.Format("Hello {0}!", name);
    }
}

and
C#
public interface IService
{
    [OperationContract]
    string SayHello(string name);
}

What I need to have is something like this...
C#
HttpWebRequest request = WebRequest.Create("http://localhost:56779/BeSTService.svc/SayHello") as HttpWebRequest;
            string parameters = "{\"name\":\"Umais\"}"; // or any other way to send parameters
            request.Method = "POST";
            request.ContentLength = 0;
            request.ContentType = "application/json";
            if (!string.IsNullOrEmpty(parameters))
            {
                byte[] byteArray = Encoding.UTF8.GetBytes(parameters);
                request.ContentLength = byteArray.Length;
                Stream dataStream = request.GetRequestStream();
                dataStream.Write(byteArray, 0, byteArray.Length);
                dataStream.Close();
            }
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();

I need to use wsHttpBinding as I'm unable to implement the same authentication in webHttpBinding. The wsHttpBinding is working (with authentication) in windows application; however, I need to call this service as HttpWebResponse,HttpWebRequest as well. Please help me out here! I get "Bad Request" error.
Tags: C#, WCF

Plain Text
ASM
ASP
ASP.NET
BASIC
BAT
C#
C++
COBOL
CoffeeScript
CSS
Dart
dbase
F#
FORTRAN
HTML
Java
Javascript
Kotlin
Lua
MIDL
MSIL
ObjectiveC
Pascal
PERL
PHP
PowerShell
Python
Razor
Ruby
Scala
Shell
SLN
SQL
Swift
T4
Terminal
TypeScript
VB
VBScript
XML
YAML

Preview



When answering a question please:
  1. Read the question carefully.
  2. Understand that English isn't everyone's first language so be lenient of bad spelling and grammar.
  3. If a question is poorly phrased then either ask for clarification, ignore it, or edit the question and fix the problem. Insults are not welcome.
  4. Don't tell someone to read the manual. Chances are they have and don't get it. Provide an answer or move on to the next question.
Let's work to help developers, not make them feel stupid.
Please note that all posts will be submitted under the http://www.codeproject.com/info/cpol10.aspx.



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900