4
11

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

LinuxでMonoを使ってC#をコンパイル・実行する

Last updated at Posted at 2016-09-06

目標:

  • NuGetを使ってRestSharpをインストールする
  • RestSharpを使ってHTTP POSTする

Monoをインストール

自分はArch Linuxなので

pacman -S mono

でインストール。他のディストロの場合はyumか何かで探してみてください。

NuGetをインストールする

wget --no-check-certificate https://nuget.org/nuget.exe
mozroots --import --machine --sync
certmgr -ssl -m https://go.microsoft.com
certmgr -ssl -m https://nugetgallery.blob.core.windows.net
certmgr -ssl -m https://nuget.org

途中何か聞かれるのでyesと入力。

こちらを参考にさせていただいた。
http://symfoware.blog68.fc2.com/blog-entry-1750.html

※mozrootsとcertmgrはmonoパッケージに含まれるコマンド

NuGetでRestSharpをGET

mono nuget.exe install RestSharp

カレントディレクトリの下にRestSharp.105.2.3がダウンロードされた。

DLLへのパスを通す

export MONO_PATH=./RestSharp.105.2.3/lib/net452

コードを書く

Test.cs
using System;
using RestSharp;

class Test
{
    public static void Main()
    {
        var client = new RestClient("http://httpbin.org");

        var request = new RestRequest("/post", Method.POST);
        request.AddParameter("hoge", "123"); // adds to POST or URL querystring based on Method
        request.AddParameter("sage", "456"); // adds to POST or URL querystring based on Method

        // execute the request
        IRestResponse response = client.Execute(request);
        var content = response.Content; // raw content as string

        Console.WriteLine(content);
    }
}

RestSharpの使い方についてはこちら:
http://restsharp.org/

ビルドして実行

$ mcs -reference:./RestSharp.105.2.3/lib/net46/RestSharp.dll Test.cs

### ./Test.exe でも実行できる
$ mono Test.exe

{
  "args": {}, 
  "data": "", 
  "files": {}, 
  "form": {
    "hoge": "123", 
    "sage": "456"
  }, 
  "headers": {
    "Accept": "application/json, application/xml, text/json, text/x-json, text/javascript, text/xml", 
    "Accept-Encoding": "gzip, deflate", 
    "Content-Length": "17", 
    "Content-Type": "application/x-www-form-urlencoded", 
    "Host": "httpbin.org", 
    "User-Agent": "RestSharp/105.2.3.0"
  }, 
  "json": null, 
  "url": "http://httpbin.org/post"
}

Test.exeRestSharp.dllを同じディレクトリに置いておけばMONO_PATHはセットしなくてもいい模様
配布時の推奨ディレクトリ構造がここに書いてある:
http://www.mono-project.com/docs/getting-started/application-deployment/

REPLを使う

$ csharp
Mono C# Shell, type "help;" for help

Enter statements below.
csharp> DateTime.Now 
2016/09/17 12:30:35                   
csharp> 

補完も効くので便利。

4
11
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
11

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?