Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
156 views
in Technique[技术] by (71.8m points)

c# - Not able to use REST API for Service Bus for Windows Server 1.1 (OnPremises)

I am using the Window Server Service Bus 1.1. I am able to generate the OAuth token from the Window Server Service Bus using the following base address

  string baseAddressHttp = "https://" + ServerName + ":9355/" + Namespace + "/$STS/OAuth/"; 

For Window Azure Service Bus for sending a message to queue i can POST a request on the following queue address

        string serviceNamespace = "ServiceBusDefaultNamespace";
        string queueName = "SampleQueuName";
        string message ="This is my first message";
        string queueAddress = "https://" + serviceNamespace + ".servicebus.windows.net/"+ queueName + "/messages";
        WebClient webClient = new WebClient();
        webClient.Headers[HttpRequestHeader.Authorization] = token;
        webClient.UploadData(baseAddress, "POST", Encoding.UTF8.GetBytes(message));

But for window Server Service Bus what same technique doesn't work.

Does Window Server Service Bus 1.1 support the REST API? Any help will be really appreciated.

Thanks in advance!!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

yes it does support it. We are using it.

  1. I think your default namespace endpoint is wrong - you dont need .servicebus.windows.net
  2. you need to get a token from the sts first using a username and password of a user that has listen or send permissions on service bus.
  3. the username and password of the service bus user must be posted in a specific format.
  4. Then you need to add the token that is returned into the authorisation header and make your actual send or listen request to the /messages endpoint.
  5. This code should do it:

    private const string DefaultNamespace = "https://yoursbserver:9355/servicebusdefaultnamespace";
    private const string QueueEndpoint = "https://yoursbserver:9355/servicebusdefaultnamespace/YourQueueNameOrTopicName/messages/?timeout=60";
    
    private static void Main()
    {
        var token = GetOAuthTokenFromSts(new Uri(DefaultNamespace), "usernamewithpermissiononServiceBus", "password", TimeSpan.FromMinutes(10));
        var messageXml = CreateXml();
        SendMessage(token, messageXml);
    
        Console.WriteLine("Successfully posted message!");
        Console.ReadLine();
    }
    
    private static string CreateMessage()
    {
        return "<SomeMessage xmlns='MyNamespace'></SomeMessage>";
    }
    
    public static string GetOAuthTokenFromSts(Uri namespaceBaseAddress, string userName, string userPassword, TimeSpan timeout)
    {
        const string stsPath = "$STS/OAuth/";
    
        var requestUri = new Uri(namespaceBaseAddress, stsPath);
        var requestContent = GetRequestContent(namespaceBaseAddress, userName, userPassword);
        var request = CreateRequest(timeout, requestUri, requestContent);
        return GetAccessToken(request, requestContent);
    }
    
    private static HttpWebRequest CreateRequest(TimeSpan timeout, Uri requestUri, byte[] requestContent)
    {
        var request = WebRequest.Create(requestUri) as HttpWebRequest;
        request.ServicePoint.MaxIdleTime = 5000;
        request.AllowAutoRedirect = true;
        request.MaximumAutomaticRedirections = 1;
        request.Method = "POST";
        request.ContentType = "application/x-www-form-urlencoded";
        request.ContentLength = requestContent.Length;
        request.Timeout = Convert.ToInt32(timeout.TotalMilliseconds,
                                          CultureInfo.InvariantCulture);
        return request;
    }
    
    private static byte[] GetRequestContent(Uri namespaceBaseAddress, string userName, string userPassword)
    {
        const string clientPasswordFormat = "grant_type=authorization_code&client_id={0}&client_secret={1}&scope={2}";
        var requestContent = string.Format(CultureInfo.InvariantCulture,
                                              clientPasswordFormat, HttpUtility.UrlEncode(userName),
                                              HttpUtility.UrlEncode(userPassword),
                                              HttpUtility.UrlEncode(namespaceBaseAddress.AbsoluteUri));
        return Encoding.UTF8.GetBytes(requestContent);
    }
    
    private static string GetAccessToken(HttpWebRequest request, byte[] requestContent)
    {
        string accessToken;
        using (var requestStream = request.GetRequestStream())
        {
            requestStream.Write(requestContent, 0, requestContent.Length);
        }
    
        using (var response = request.GetResponse() as HttpWebResponse)
        using (var stream = response.GetResponseStream())
        using (var reader = new StreamReader(stream, Encoding.UTF8))
        {
            accessToken = reader.ReadToEnd();
        }
    
        return string.Format(CultureInfo.InvariantCulture, "WRAP access_token="{0}"", accessToken);
    }
    
    private static void SendMessage(string token, string message)
    {
        var webClient = new WebClient();
        webClient.Headers[HttpRequestHeader.Authorization] = token;
        webClient.UploadData(QueueEndpoint, "POST", Encoding.UTF8.GetBytes(message));
    }
    

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...