在c#中调用web api中控制器的正确URI是什么?

时间:2016-08-31 13:16:23

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

我的控制器

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using MySql.Data;
using MySql.Data.MySqlClient;
using System.Data;
using System.Configuration;

namespace WebAPIDemo.Controllers
{
    public class WebAPIDemoController : ApiController
    {           
        public class Users
        {
            string connectionstring = ConfigurationManager.ConnectionStrings["MySqlConnectionString"].ConnectionString.ToString();
            MySqlDataReader reader = null;
            MySqlConnection connection;

            public int Id;
            public string FirstName;

            [ActionName("GetUser")]
            [Route("api/WebAPIDemo/GetUserById")]

            [HttpGet]
            public Users GetUserById(int UserId)
            {       
                using (connection = new MySqlConnection(connectionstring))
                {     
                    MySqlCommand sqlCmd = new MySqlCommand();
                    sqlCmd.CommandType = CommandType.Text;
                    sqlCmd.CommandText = "Select * from User where id='"+ UserId + "' ";
                    sqlCmd.Connection = connection;
                    connection.Open();
                    reader = sqlCmd.ExecuteReader();
                    Users usr = new Users();
                    while (reader.Read())
                    {    
                        usr.FirstName = (Convert.IsDBNull(reader["FirstName"]) ? "" : Convert.ToString(reader["FirstName"]));
                        connection.Close();
                    }
                    return usr;                    
                 }
            }    
        }
    }
}

web api config route

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Web.Http;
using Microsoft.Owin.Security.OAuth;
using Newtonsoft.Json.Serialization;

namespace WebAPIDemo
{
    public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            // Web API configuration and services
            // Configure Web API to use only bearer token authentication.
            //config.SuppressDefaultHostAuthentication();
            //config.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType));

            // Web API routes
            config.MapHttpAttributeRoutes();



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

URI

http://localhost:53869/api/WebAPIDemo/GetUserById?id=96

错误消息

<Error>
<Message>
No HTTP resource was found that matches the request URI 'http://localhost:53869/api/WebAPIDemo/GetUserById?id=96'.
</Message>
<MessageDetail>
No action was found on the controller 'WebAPIDemo' that matches the request.
</MessageDetail>
</Error>

我是web api的新手.. 有些身体可以帮助...... 我找不到错误是什么...... 我已经阅读了谷歌的一些文章,但无法解决.......

2 个答案:

答案 0 :(得分:0)

您的操作方法不在控制器内;它在班级Users内。将它向上移动一级,然后找到它(必须是WebAPIDemoController的方法)。对于此示例,我从控制器中提取了Users类。

public class Users
{        
    public int Id;
    public string FirstName;
}

public class WebAPIDemoController : ApiController
{               
    [ActionName("GetUser")]
    [Route("api/WebAPIDemo/GetUserById")]

    [HttpGet]
    public Users GetUserById(int UserId)
    {       
        string connectionstring = ConfigurationManager.ConnectionStrings["MySqlConnectionString"].ConnectionString.ToString();
        MySqlDataReader reader = null;
        MySqlConnection connection;

        using (connection = new MySqlConnection(connectionstring))
        {     
            MySqlCommand sqlCmd = new MySqlCommand();
            sqlCmd.CommandType = CommandType.Text;
            sqlCmd.CommandText = "Select * from User where id='"+ UserId + "' ";
            sqlCmd.Connection = connection;
            connection.Open();
            reader = sqlCmd.ExecuteReader();
            Users usr = new Users();
            while (reader.Read())
            {    
                usr.FirstName = (Convert.IsDBNull(reader["FirstName"]) ? "" : Convert.ToString(reader["FirstName"]));
                connection.Close();
            }
            return usr;                                     
        }    
    }   
}

答案 1 :(得分:0)

将关注点(Soc)和单一责任原则(SRP)应用于您的示例,您需要分解您的类,以便他们不会对太多事情负责。

将用户(模型)类分解为自己的类

public class User {
    public int Id;
    public string FirstName;
} 

将数据访问提取到自己的类中。

public class UsersContext {
    string connectionstring = ConfigurationManager.ConnectionStrings["MySqlConnectionString"].ConnectionString.ToString();

    public User GetUserById(int UserId) {
        using (var connection = new MySqlConnection(connectionstring)) {
            using (var command = new MySqlCommand()) {
                command.CommandType = CommandType.Text;
                command.CommandText = "Select * from User where id='@UserId'";
                command.Connection = connection;

                var parameter = command.CreateParameter();
                parameter.ParameterName = "@UserId";
                parameter.Value = UserId;

                command.Parameters.Add(parameter);

                connection.Open();
                using (var reader = command.ExecuteReader()) {
                    var user = new User();
                    while (reader.Read()) {
                        user.FirstName = (Convert.IsDBNull(reader["FirstName"]) ? "" : Convert.ToString(reader["FirstName"]));
                    }
                    return user;
                }
            }
        }
    }
}

然后让 ApiController 专注于处理请求

public class WebAPIDemoController : ApiController {

    [ActionName("GetUser")]
    [HttpGet]
    [Route("api/WebAPIDemo/GetUserById")]
    public IHttpActionResult GetUserById(int id) {
        var context = new UsersContext();

        var user = context.GetUserById(id);

        return Ok(user);
    }
}

为了允许以下请求

http://localhost:53869/api/WebAPIDemo/GetUserById?id=96

要与路由引擎匹配,您需要确保参数匹配。在您的示例中,您使用查询字符串?id=96进行了调用,但在您的操作中,您有

GetUserById(int UserId) { ... }

将查询字符串更新为?UserId=96或将操作参数更改为

GetUserById(int id) { ... } 
ApiController 中的

。他们需要匹配,以便在发出请求时路由匹配它们。