11

c# で次の cURL リクエストを実行したい:

curl -u admin:geoserver -v -XPOST -H 'Content-type: text/xml' \
   -d '<workspace><name>acme</name></workspace>' \
   http://localhost:8080/geoserver/rest/workspaces

私は WebRequest を使用してみました:

string url = "http://localhost:8080/geoserver/rest/workspaces";
WebRequest request = WebRequest.Create(url);

request.ContentType = "Content-type: text/xml";
request.Method = "POST";
request.Credentials = new NetworkCredential("admin", "geoserver");

byte[] buffer = Encoding.GetEncoding("UTF-8").GetBytes("<workspace><name>my_workspace</name></workspace>");
Stream reqstr = request.GetRequestStream();
reqstr.Write(buffer, 0, buffer.Length);
reqstr.Close();

WebResponse response = request.GetResponse();
...

しかし、次のエラーが表示されます: (400) リクエストが正しくありません。

リクエストの資格情報を変更し、ヘッダーに認証を追加すると:

string url = "http://localhost:8080/geoserver/rest/workspaces";
WebRequest request = WebRequest.Create(url);

request.ContentType = "Content-type: text/xml";
request.Method = "POST";
string authInfo = "admin:geoserver";
request.Headers["Authorization"] = "Basic " + authInfo;

byte[] buffer = Encoding.GetEncoding("UTF-8").GetBytes("<workspace><name>my_workspace</name></workspace>");
Stream reqstr = request.GetRequestStream();
reqstr.Write(buffer, 0, buffer.Length);
reqstr.Close();

WebResponse response = request.GetResponse();
...

それから私は得る: (401) 無許可。

私の質問は、WebClient や HttpWebRequest などの別の C# クラスを使用する必要がありますか、それとも .NET 用のカール バインディングを使用する必要がありますか?

すべてのコメントまたはガイダンスをいただければ幸いです。

4

4 に答える 4

12

HTTP基本認証では、「基本」以降のすべてがBase64でエンコードされる必要があるため、試してください

request.Headers["Authorization"] = "Basic " + 
    Convert.ToBase64String(Encoding.ASCII.GetBytes(authInfo));
于 2011-03-01T11:08:36.587 に答える
10

私の質問に対する解決策は、ContentTypeプロパティを変更することでした。ContentType を

request.ContentType = "text/xml";

Anton Gogolevが提案したように、最後の例でauthInfoをBase64Stringに変換すると、リクエストは両方のケースで機能します。

于 2011-03-02T10:24:26.750 に答える
2

使用:

request.ContentType = "application/xml";

request.Credentials = new NetworkCredential(GEOSERVER_USER, GEOSERVER_PASSWD);

も機能します。2 番目は、認証情報を設定します。

于 2012-06-21T12:51:16.200 に答える