Web APIがあり、2つのメソッドがあります。1つはパラメーターなし、2つは異なるタイプのパラメーター(stringとint)です。文字列メソッドを呼び出すときに機能しません...ここで何が欠けていますか?
public class MyControllerController : ApiController
{
public IHttpActionResult GetInt(int id)
{
return Ok(1);
}
public IHttpActionResult GetString(string test)
{
return Ok("it worked");
}
}
WebApiConfig.cs:
public static void Register(HttpConfiguration config)
{
// Web API configuration and services
// Web API routes
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
私の電話:
/ api/MyController/MyString //作業しない
/ api/MyController/1 // work
次のエラーが表示されます。
パラメーターディクショナリには、 'TestAngular.Controllers.MyControllerController'のメソッド 'System.Web.Http.IHttpActionResult GetInt(Int32)'のnullを許可しない型 'System.Int32'のパラメーター 'id'のnullエントリが含まれています。オプションのパラメーターは、参照型、null許容型、またはオプションのパラメーターとして宣言する必要があります。
私のリクエストには何が欠けていますか?
Uriを変更する必要があります
/api/MyController
/api/MyController/string
/api/MyController/1
メソッドを指定する必要はありません。
詳細を確認するには、asp.netでこれをご覧ください tutorial .
また、このURIは動作するはずです:
api/MyController/GetAll
api/MyController/GetString?param=string
api/MyController/GetInt?param=1
これははるかに明確で、常に機能するはずです。ルーティング動作を使用します。
こちらをご覧ください: http://www.asp.net/web-api/overview/web-api-routing-and-actions/routing-and-action-selection
ここに私の解決策があります:webapiconfig.csファイルのデフォルトルートを変更せずに
文字列関数にルートを追加するだけです:
[Route("Api/MyController/GetString/{test}")]
public IHttpActionResult GetString(string test)
http:// localhost:49609/api/MyController/GetString/stringtest
あなたがこれを投稿してからしばらく経ちましたが、答えがあると思います。まず、2つの問題があります。まず、ピンバックが指摘したように、2つの異なるエンドポイントに同じルートを使用することはできません。
ただし、int
メソッドを削除しただけでも、問題が発生します。覚えておいてください:デフォルトのルートは次のようになります:api/{controller}/{id}パラメーターをバインドするには、「test」ではなく「id」と呼ばれる必要があります。
これに署名を変更します。
public IHttpActionResult GetString(string id)
そしてそれは動作します。 (webapiconfig.csファイルで{id}
を{test}
に変更することもできます)。
また、本文の文字列パラメータを取ることができます
string body;
using (var sr = new StreamReader(Request.Body))
body = sr.ReadToEnd();