当我试图从另一个网站访问我的WebAPI代码时,出现以下错误。
这是返回的JSON消息。
"Message":"No HTTP resource was found that matches the request URI
'http://localhost:47845/api/Test?samAccountName=aasdf&success=True&permissionName=bla'.","MessageDetail":
"No action was found on the controller 'Test' that matches the request."
当我直接访问网站时,http://MyServer/ApiToHit/api/Values?samAccountName=someAccount&success=True&permissionName=MyPermission,会得到一个成功的字符串。
但是当我使用以下代码访问时,会得到上面的错误信息。
using (var client = new HttpClient(new HttpClientHandler { UseDefaultCredentials = true }))
{
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
var values = HttpUtility.UrlDecode(string.Format(
CultureInfo.InvariantCulture, ConfigurationManager.AppSettings["PathToParameters"].ToString(),
"someAccount".ToUpper(CultureInfo.InvariantCulture),
true.ToString(),
"MyPermission".ToUpper(CultureInfo.InvariantCulture)));
lblResult.Text = string.Empty;
var newUrl = new Uri(ConfigurationManager.AppSettings["Url"].ToString() + values);
// HTTP GET
var response = await client.GetAsync(newUrl, HttpCompletionOption.ResponseHeadersRead).ConfigureAwait(false);
//var response = await client.GetAsync(values, HttpCompletionOption.ResponseHeadersRead).ConfigureAwait(false);
this.lblResult.Text = await response.Content.ReadAsStringAsync();
}
这是我的API控制器
public class TestController : ApiController
{
// GET: api/Test
public string Get(string samAccountName, bool success, string permissionName)
{
var returnValue = "Success";
return returnValue;
}
}
这是我的路由信息
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
}
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 }
);
}
RouteConfig
中难道不应该有一个针对TestController
的MapRoute
吗?你上面展示的只是针对HomeController
的。 - ShivaWebApiConfig.cs
文件中。 - Nkosi