Create Hybrid Connection Azure Rest API - c#

I am trying to create a hybrid connection in Azure BizTalk service using rest API. Nevertheless, I am receiving this error:
<Error xmlns="http://schemas.microsoft.com/windowsazure" xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
<Code>InternalError</Code>
<Message>The server encountered an internal error. Please retry the request.</Message>
</Error>
Request:
PUT https://management.core.windows.net/36be0e4b-0a10-4b12-8b1c-6aefd3df3fe9/cloudservices/Default-BizTalk-South-Central-US/resources/biztalkservices/~/biztalk/qwbiztalkservice/hybridconnection/namenewhybridconnection HTTP/1.1
Accept: application/xml
x-ms-version: 2012-08-01
Content-Type: application/xml; charset=utf-8
Host: management.core.windows.net
Content-Length: 152
Expect: 100-continue
Connection: Keep-Alive
<HybridConnectionInput xmlns=\"http://schemas.microsoft.com/windowsazure\">
<HostName>myhost</HostName>
<Port>443</Port>
</HybridConnectionInput>
Documentation reference: https://msdn.microsoft.com/en-us/library/azure/dn743828.aspx

Related

asp.net core 2.2 posting file results in http/415 unsopported mediatype

From postman I'm trying to post a file to an asp.net core 2.2 api-controller.
POST /api/epd/noshow/uploadfile HTTP/1.1
Host: localhost:44361
User-Agent: PostmanRuntime/7.11.0
Accept: */*
Cache-Control: no-cache
Postman-Token: 3d633228-2554-442b-84f4-4e8214972886,a8f994f4-973e-411f-b96b-778af2c082b4
Host: localhost:44361
accept-encoding: gzip, deflate
content-type: multipart/form-data; boundary=--------------------------201375848683546790642901
content-length: 237
Connection: keep-alive
cache-control: no-cache
Content-Type: multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW
Content-Disposition: form-data; name="file"; filename="C:\temp\caldr.json
------WebKitFormBoundary7MA4YWxkTrZu0gW--
The api-controller method
[HttpPost]
[AllowAnonymous]
public IActionResult UploadFile([FromForm]IFormFile file)
{
return Ok();
}
I've already tried FromForm, FromBody, nothing. Setting content-type in postman, not setting the content-type in postman always returns the same error.
Any suggestions ?
That is simple than expected :) You to send the request body in a form data. Here, this example shows only the simple file post call with ASp.NET Core 2.2 - WebAapi
Postman:
API:
Found the problem and solution. Just for reference if someone else encounters the same mind boggling problem.
On the 'grandmother' class of the controller, there is the following attribute :
[Consumes("application/json")]
of course form-data was not accepted :-)
override this default behaviour by adding the following attribute to the action
[Consumes("multipart/form-data")]

401 Unauthorized - token not being accepted

I'm successfully using the Graph API for a variety of things but I need to access to the OneNote API to perform student and teacher add/remove operations on Class Notebooks. When I request a token the same way that I do for Graph with the https://www.onenote.com resource it provides one but when I try to use it to access the OneNote API no matter what (valid) request I send I get 401 - "The request does not contain a valid authentication token."
I've tried using the v1.0 endpoint to generate a token instead with the same results.
My token requests:
POST https://login.microsoftonline.com/{my tenant}/oauth2/v2.0/token HTTP/1.1
Accept: application/json
Content-Type: application/x-www-form-urlencoded
Host: login.microsoftonline.com
Content-Length: 213
Expect: 100-continue
Connection: Keep-Alive
grant_type=client_credentials&client_id={my appid}&client_secret={my secret}&tenant={my tenant}&scope=https%3A%2F%2Fwww.onenote.com%2F.default
OR
POST https://login.microsoftonline.com/{my tenant}/oauth2/token HTTP/1.1
Accept: application/json
Content-Type: application/x-www-form-urlencoded
Host: login.microsoftonline.com
Content-Length: 161
Expect: 100-continue
grant_type=client_credentials&client_id={my appid}&client_secret={my secret}&resource=https%3A%2F%2Fwww.onenote.com
Both return something containing an access_token, like:
{"token_type":"Bearer","expires_in":"3600","ext_expires_in":"3600","expires_on":"1543513719","not_before":"1543509819","resource":"https://www.onenote.com","access_token":"{a token}"}
Request:
GET https://www.onenote.com/api/v1.0/myorganization/groups/{group id}/notes/ HTTP/1.1
ContentType: application/json
Authorization: Bearer {token returned from /token request}
Cache-Control: no-store, no-cache
Host: www.onenote.com
Response:
code=40001
message=The request does not contain a valid authentication token.
For reference, this question is basically a follow-up to: Adding Students with the API and Class Notebook
You're on the right track.
Resource is the right way with the 1.0 auth endpoint.
Scopes need to be registered on the app portal, so you'll need to go back in and add OneNote scopes in the portal.
I'm not 100% sure, but IIRC the resource for onenote might require a trailing '/'.

Provide AntiForgery Token with System.Net.Http.HttpClient and MVC

I have a WPF (could be any winform I guess) app that tries to login to a standard MVC 5 website using a HttpClient.
Normally I can login successfully with a call to PostAsync() where I provide the UserName and Password params in a HttpContent!
However, when I add the [ValidateAntiForgeryToken] to my controller's Login (POST) action, the PostAsync() call fails with Internal Server Error.
I have tried collecting the "__RequestVerificationToken" from a simple GET request and sending it with my POST request by adding it to the POST params, the Header of the request or the HttpHandler's CookieContainer (or any combination of the three) but still I get error 500 from the server.
I know it can be done with HttpWebRequests (apparently) but I don't know what I'm missing when using a HttpClient. I also don't know what exactly went wrong on the server side.. or how to check that since the code never reaches my controller method.
Did someone else try this by any chance?
EDIT 1:
I'm adding the raw data sent by the browser for both GET and POST:
GET http://localhost:57457/Account/Login HTTP/1.1
Accept: text/html, application/xhtml+xml, */*
Referer: http://localhost:57457/Account/Login
Accept-Language: en-US
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; rv:11.0) like Gecko
Accept-Encoding: gzip, deflate
Connection: Keep-Alive
DNT: 1
Host: localhost:57457
Cookie: NavigationTreeViewState=%5b%7b%27N0_1%27%3a%27T%27%2c%27N0%27%3a%27T%27%7d%2c%27N0_1_2%27%2c%7b%7d%5d; style=default; __RequestVerificationToken=Bak42Ga5sHJitYlmut6OgvmqXNmP7kKQRNaMSsLMAUh86iHGGmz5pnNfz_soKu46Wax9sG23arPOTnSh1bvaWyWqQ9NH4GJxFmendW8VFTg1
RESPONSE:
HTTP/1.1 200 OK
Cache-Control: private
Content-Type: text/html; charset=utf-8
Content-Encoding: gzip
Vary: Accept-Encoding
Server: Microsoft-IIS/8.0
X-AspNetMvc-Version: 5.2
X-Frame-Options: SAMEORIGIN
X-AspNet-Version: 4.0.30319
X-SourceFiles: =?UTF-8?B?RDpcRUJTLkNvZGVcUHJvamVjdHNcQ1ZSUE9TX1dlYlNpdGVcQ1ZSUE9TX1dlYlNpdGVcQWNjb3VudFxMb2dpbg==?=
X-Powered-By: ASP.NET
Date: Thu, 04 Dec 2014 10:00:00 GMT
Content-Length: 1734
[View page content]
POST http://localhost:57457/Account/Login HTTP/1.1
Accept: text/html, application/xhtml+xml, */*
Referer: http://localhost:57457/Account/Login
Accept-Language: en-US
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; rv:11.0) like Gecko
Content-Type: application/x-www-form-urlencoded
Accept-Encoding: gzip, deflate
Connection: Keep-Alive
Content-Length: 180
DNT: 1
Host: localhost:57457
Pragma: no-cache
Cookie: NavigationTreeViewState=%5b%7b%27N0_1%27%3a%27T%27%2c%27N0%27%3a%27T%27%7d%2c%27N0_1_2%27%2c%7b%7d%5d; style=default; __RequestVerificationToken=Bak42Ga5sHJitYlmut6OgvmqXNmP7kKQRNaMSsLMAUh86iHGGmz5pnNfz_soKu46Wax9sG23arPOTnSh1bvaWyWqQ9NH4GJxFmendW8VFTg1
__RequestVerificationToken=Bak42Ga5sHJitYlmut6OgvmqXNmP7kKQRNaMSsLMAUh86iHGGmz5pnNfz_soKu46Wax9sG23arPOTnSh1bvaWyWqQ9NH4GJxFmendW8VFTg1&UserName=test&Password=test
RESPONSE:
HTTP/1.1 400 Bad request (user/password for testing purposes only)
Cache-Control: private
Content-Type: text/html; charset=utf-8
Server: Microsoft-IIS/8.0
X-AspNetMvc-Version: 5.2
X-Frame-Options: SAMEORIGIN
X-AspNet-Version: 4.0.30319
X-SourceFiles: =?UTF-8?B?RDpcRUJTLkNvZGVcUHJvamVjdHNcQ1ZSUE9TX1dlYlNpdGVcQ1ZSUE9TX1dlYlNpdGVcQWNjb3VudFxMb2dpbg==?=
X-Powered-By: ASP.NET
Date: Thu, 04 Dec 2014 10:00:00 GMT
Content-Length: 4434
[View page content]
EDIT 2:
This is what my app sends for GET and POST:
GET http://localhost:57457/Account/Login HTTP/1.1
Host: localhost:57457
Connection: Keep-Alive
POST http://localhost:57457/Account/Login HTTP/1.1
Content-Type: application/x-www-form-urlencoded
Host: localhost:57457
Cookie: __RequestVerificationToken=df9nBSP_J1IiLrv84RwrkmvbYBrnH4iqv97wRvz6HMPLWBhgI4XzGeAFcschovHwD8mTtHU6xrmVxz1Ku96_BaoB79le_vLTcrgGemU4gjc1
Content-Length: 163
Expect: 100-continue
__RequestVerificationToken=df9nBSP_J1IiLrv84RwrkmvbYBrnH4iqv97wRvz6HMPLWBhgI4XzGeAFcschovHwD8mTtHU6xrmVxz1Ku96_BaoB79le_vLTcrgGemU4gjc1&UserName=test&Password=test
And finally this is the error:
[HttpAntiForgeryException (0x80004005): Validation of the provided anti-forgery token failed. The cookie "__RequestVerificationToken" and the form field "__RequestVerificationToken" were swapped.]
Thanks!
You d probably need to include aspnet session id cookie with your requests
EDIT:
OK ur right, it is not the session id, but you need two token to send back to your post action.
I think what you re doing wrong is using same value for both tokens, but they should be different, altho name of both tokens is __RequestVerificationToken.
Token grabbed from cookie should be send back as cookie and token grabbed from form field goes back as form field.
It's because you're missing the anti-forgery token from HtmlHelper.AntiForgeryToken() in your POST from your application.
You'll need to load a page from your WPF application with HtmlHelper.AntiForgeryToken() on the view. Then take the value of the hidden input element with the name __RequestVerificationToken and attach it to your login POST request to the server.

C#: HttpClient, The server committed a protocol violation. Section=ResponseStatusLine

I'm using the HttpClient class to communicate to a web service in my WPF application.
When I make consecutive GET requests on the same connection, everything works fine. However, when I make consecutive PUT/PATCH requests on the same connection, the first request executes accurately and I receive a response but the second request does not include the body in the request and I receive the infamous error of "The server committed a protocol violation. Section=ResponseStatusLine".
My requests do complete successfully if I manually close the connection after every request by adding Connection: close to the header. This "solution" is a bad pattern and performance will not scale appropriately.
Below is a debranded version of a list of my TCP Stream Output from the requests being sent:
Wireshark: Follow TCP Stream Output
GET /domain/api/tenant/current/object?objectName=Lizbot HTTP/1.1
Accept: application/json
HTTP/1.1 200 OK
Content-Type: application/json; charset=utf-8
Content-Length: 50
{"Data":[{"Id":123,"ObjectName":"Lizbot","Date":null}],"Errors":[]}
PATCH /domain/api/tenant/current/object/123 HTTP/1.1
Accept: application/json
Content-Type: application/json; charset=utf-8
Content-Length: 50
{"Id":123,"ObjectName":"Lizbot","Date":null}
HTTP/1.1 204 No Content
Content-Type: application/json; charset=utf-8
{"Data":null,"Errors":[]}
PATCH /domain/api/tenant/current/object/123/otherObject HTTP/1.1
Accept: application/json
Content-Type: application/json; charset=utf-8
HTTP/1.1 400 Bad Request</b>
Content-Type: text/html; charset=us-ascii
Connection: close
Content-Length: 311
Notice that the second PATCH is missing the object it's supposed to patch with. If I change the order of the PATCHing, the second PATCH is still missing its object.
This error appears to be common with a few known solutions which I have tried. They consist of this solution which involves setting the useUnsafeHeaderParsing property to TRUE and setting the Keep-Alive property to FALSE in the Web.Config. I also tried the solution of setting these properties in this manner shown below:
ServicePointManager.DefaultConnectionLimit = 2;
ServicePointManager.Expect100Continue = false;
None of these solutions worked. It should be noted that when using the Http Debugging proxy tool, Fiddler, to capture these requests, I don't receive any errors.
So what I am asking for is if anyone knows a good solution to alleviate this error so I can make multiple requests in a connection without losing the body of an update. If more details are needed, I am happy to supply them.
After much debugging and reading, I realized I was trying to edit the Web.Config file of the WPF application instead of the app.config file!
So if you drop this code in the app.config file at the root of the configuration tag for a WPF application, it fixes the problem.
<system.net>
<settings>
<httpWebRequest useUnsafeHeaderParsing = "true"/>
</settings>
</system.net>
The underlying problem is that the PATCH response includes content within the body of the response. Ensure that the server does not send content when sending a 204 No Content.

RESTSharp empty body on ExecuteAsyncPost versus ExecutePost

I'm using RestSharp to build a Rest access to my MVC entry points (actually so I can use them from monotouch, but right now I'm testing on Windows 7, vs2010, .net 4, RestSharp 104.1)
if I create a request and call
client.ExecuteAsPost<Model.Client>( request );
it works, I can see in fiddler the raw packet
POST http://localhost.:49165/Services/Client/ClientAdminService/FindClient HTTP/1.1
Timestamp: Monday, March 18, 2013 1:56:02 AM
X-PS-Authentication: YADAYADA:<deleted for brevity>==
Accept: application/xml
User-Agent: RestSharp 104.1.0.0
Content-Type: application/xml; charset=utf-8
Host: localhost.:49165
Content-Length: 256
Accept-Encoding: gzip, deflate
Connection: Keep-Alive
<Client xmlns="http://schemas.datacontract.org/2004/07/PSRMWebService.Model.Version1" xmlns:i="http://www.w3.org/2001/XMLSchema-instance"><ID>0</ID><MailingAddress i:nil="true"/><Mask>Name</Mask><Name>Rykercom</Name><PhysicalAddress i:nil="true"/></Client>
as you can see at the end is the serialized data blob I need to send to the server (of type Model.Client) this is added to the request using
Request.AddParameter("application/xml; charset=utf-8", DataPacket, RestSharp.ParameterType.RequestBody);
where DataPacket is the serialized blob created using a DataContractSerializer
Now if I change the code to call
Client.ExecuteAsyncPost<Model.Client>(Request, (response, handle) => { OnFindClientAsyncComplete(response, handle, Callback ); }, "POST");
Using Fiddler I get quite a different packet with no Body, no content type, and therefore a failed response from the server.
POST http://localhost.:49165/Services/Client/ClientAdminService/FindClient HTTP/1.1
Timestamp: Monday, March 18, 2013 2:35:08 AM
X-PS-Authentication: YADAYADA:<deleted for bevity>==
Accept: application/xml
User-Agent: RestSharp 104.1.0.0
Host: localhost.:49165
Content-Length: 0
Accept-Encoding: gzip, deflate
Connection: Keep-Alive
the X-PS-Authentication is just a custom auth string. Anyone any ideas why the async call is leaving me with an empty message body ?
The simple answer is clone the current github repository for rest sharp and build it yourself. It appears the fix for executeasync is already in the tree.
Any chance who ever own the Nuget package can update it to the lastest sources ?
Thanks

Categories