收到"没有找到资源"使用HttpClient

时间:2017-03-30 15:39:36

标签: c# asp.net-web-api2 asp.net-web-api-routing

背景

目前有一个api我已经创建了一段时间,这是一个帮助api。这个api有一个控制器,它接收一个对象,然后相应地处理它。

问题

当我打电话给我的接收api时,我收到错误以下错误信息。

  

{" Message":"未找到与请求URI匹配的HTTP资源   ' http://appdev.tenant.com/caseware32/api/DataServices/CreateDBF'"" MessageDetail":"否   在控制器上找到了行动' DataServices'匹配的   。请求"}

然而,控制器是可操作的,因为我可以调出控件中的另一个功能,它可以给我所有客户端。我确保我的路由属性与我的请求网址匹配,但仍然没有成功。

代码

发送网络广告

public static async Task<bool> CreateDBF(string dPath)
{
    var postObject = (new DBFPostModel
    {
        destinationPath = dPath,
        fileName = "CustomDBF"
    });
    List<string> uniqueID = new List<string>();
    try
    {
        string requestUrl = "http://appdev.tenant.com/caseware32/api/DataServices/CreateDBF";

        HttpClient hc = new HttpClient();

        var method = new HttpMethod("POST");

        var values = new Dictionary<string, string>()
        {
            { "Id", "6"},
            { "Name", "Skis"},
            { "Price", "100"},
            { "Category", "Sports"}
        };

        var content = new FormUrlEncodedContent(values);

        var hrm = await hc.PostAsync(requestUrl, content);
        if (hrm.IsSuccessStatusCode)
        {
            var responseData = await hrm.Content.ReadAsStringAsync();
            return true;
        }
        else
        {
            return false;
        }
    }
    catch (Exception ex)
    {
        // TODO Log 
        return false;
    }
}

接收Api

public class IncomingDbfModel
{
    public string Id { get; set; }
    public string Name { get; set; }
    public string Price { get; set; }
    public string Catergory { get; set; }
}

public class DataServicesController : ApiController
{
      [Route("api/DataServices/CreateDBF")]
    public IHttpActionResult CreateDBF(IncomingDbfModel postParam)
    {
        DatabaseServices dbServices = new DatabaseServices();
        bool success = dbServices.InsertDataIntoDBF(postParam);
        return Ok(success);
    }
}

错误

HTTP/1.1 404 Not Found
Cache-Control: no-cache
Pragma: no-cache
Content-Type: application/json; charset=utf-8
Expires: -1
Server: Microsoft-IIS/8.5
X-AspNet-Version: 4.0.30319
X-Powered-By: ASP.NET
Date: Thu, 30 Mar 2017 15:17:38 GMT
Content-Length: 232

{"Message":"No HTTP resource was found that matches the request URI 'http://appdev.tenant.com/caseware32/api/DataServices/CreateDBF'.","MessageDetail":"No action was found on the controller 'DataServices' that matches the request."}

路由配置

 public static void Register(HttpConfiguration config)
    {
        // Web API configuration and services
        config.EnableCors();

        log4net.Config.XmlConfigurator.Configure();

        // Web API routes
        config.MapHttpAttributeRoutes();

        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );
    }

1 个答案:

答案 0 :(得分:1)

默认情况下,web api的基于约定的路由模板会排除URL模板"api/{controller}/{id}"中的操作名称。上面的示例包含requestUrl = "http://appdev.tenant.com/caseware32/api/DataServices/CreateDBF"中与属性路由匹配的操作名称。 [Route("api/DataServices/CreateDBF")]

所以假设您打算使用属性路由。

HttpPost属性应用于操作,以便路由知道如何处理POST请求

public class DataServicesController : ApiController {
    //POST api/DataServices/CreateDBF
    [HttpPost]
    [Route("api/DataServices/CreateDBF")]
    public IHttpActionResult CreateDBF(IncomingDbfModel postParam) {
        DatabaseServices dbServices = new DatabaseServices();
        bool success = dbServices.InsertDataIntoDBF(postParam);
        return Ok(success);
    }
}

来源:Attribute Routing in ASP.NET Web API 2 - HTTP Methods

  

Web API还会根据请求的HTTP方法选择操作   (GET,POST等)。默认情况下,Web API会查找不区分大小写的内容   与控制器方法名称的开头匹配。

     

您可以通过使用任何方法修饰mathod来覆盖此约定   以下属性:

[HttpDelete]
[HttpGet]
[HttpHead]
[HttpOptions]
[HttpPatch]
[HttpPost]
[HttpPut]