找不到与请求URI“MyUrl”匹配的HTTP资源

时间:2016-06-06 21:15:15

标签: c# android asp.net asp.net-web-api

我创建了一个.Net网络服务:

public class UsersController : ApiController
{
    [System.Web.Http.HttpPost]
    public void Post(string value)
    {
        SqlConnection connection = new SqlConnection("Data Source=198.71.226.6;Integrated Security=False;User ID=AtallahMaroniteDB;Password=a!m?P@$$123;Database=AtallahPlesk_;Connect Timeout=15;Encrypt=False;Packet Size=4096");


        String query = "INSERT INTO Members(LastName, FirstName, Gender, MobileNumber, EmailAddress, Job, Address) VALUES " +
            "(@LastName, @FirstName, @Gender, @MobileNumber, @EmailAddress, @Job, @Address)";
        SqlCommand command = new SqlCommand(query, connection);
        try
        {
            JavaScriptSerializer json_serializer = new JavaScriptSerializer();
            PersonModel person = json_serializer.Deserialize<PersonModel>(value);

            command.Parameters.Add("@LastName", person.LastName);
            command.Parameters.Add("@FirstName", person.FirstName);
            command.Parameters.Add("@Gender", person.Gender);
            command.Parameters.Add("@MobileNumber", person.MobileNumber);
            command.Parameters.Add("@EmailAddress", person.EmailAddress);
            command.Parameters.Add("@Job", person.Job);
            command.Parameters.Add("@Address", person.Address);

            connection.Open();
            command.ExecuteNonQuery();
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.InnerException.ToString());
        }
    }
}

以下是我的路由配置:

RouteTable.Routes.MapHttpRoute(
     name: "MyApi",
     routeTemplate: "api/{controller}/{action}/{value}"
 );

当我从Android或iOS应用程序调用此Web服务时,我收到以下错误:

  

找不到与请求URI匹配的HTTP资源   'http://www.mytestdomain.com/api/users/post'

以下是android代码:

JSONObject dato = POST(person); // This method converts the Person object to JSONObject

String text = null;
try {
    HttpPost post = new HttpPost("http://www.mytestdomain.com/api/users/post");
    StringEntity entity = new StringEntity(dato.toString());
    entity.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
    post.setEntity(entity);
    HttpResponse response = httpClient.execute(post);
    HttpEntity entityResponse = response.getEntity();
    text = getASCIIContentFromEntity(entityResponse);                   
} catch ( IOException ioe ) {
    ioe.printStackTrace();
}

请注意,当我从邮递员那里调用此Web服务时,它会成功发布数据。

如果您需要任何进一步的详细信息,请与我们联系。

1 个答案:

答案 0 :(得分:3)

您需要更新路线模板,以确保获得有效的匹配请求。

以下是您的API的有效模板。请注意,这是UsersController特有的,defaults:已设置为controller = "Users",将映射到UsersController

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        // Attribute routing.
        config.MapHttpAttributeRoutes();

        // Convention-based routing.

        config.Routes.MapHttpRoute(
            name: "MyApi",
            routeTemplate: "api/users/{action}",
            defaults: new { controller = "Users" }
        );

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

从您的代码示例中,您将模型作为json发送,然后尝试在服务器上手动解析它。您可以让框架根据请求的Content-Type使用其模型绑定器解析模型。这将允许您更新您的操作以接受实际的对象模型而不是字符串。

public class UsersController : ApiController {

    //eg: POST api/users/post
    [HttpPost]
    public IHttpActionResult Post(PersonModel person) {
        if (person == null) return BadRequest();
        try
        {        
            SqlConnection connection = new SqlConnection("Data Source=198.71.226.6;Integrated Security=False;User ID=AtallahMaroniteDB;Password=a!m?P@$$123;Database=AtallahPlesk_;Connect Timeout=15;Encrypt=False;Packet Size=4096");

            String query = "INSERT INTO Members(LastName, FirstName, Gender, MobileNumber, EmailAddress, Job, Address) VALUES " +
            "(@LastName, @FirstName, @Gender, @MobileNumber, @EmailAddress, @Job, @Address)";
            SqlCommand command = new SqlCommand(query, connection);
            command.Parameters.Add("@LastName", person.LastName);
            command.Parameters.Add("@FirstName", person.FirstName);
            command.Parameters.Add("@Gender", person.Gender);
            command.Parameters.Add("@MobileNumber", person.MobileNumber);
            command.Parameters.Add("@EmailAddress", person.EmailAddress);
            command.Parameters.Add("@Job", person.Job);
            command.Parameters.Add("@Address", person.Address);

            connection.Open();
            command.ExecuteNonQuery();
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.InnerException.ToString());
            return InternalServerError();
        }
        return Ok();
    }
}

您还需要确保发送的请求正确无误,以便获得匹配

以下是原始示例请求代码段

POST  /api/users/post HTTP/1.1
Host: http://www.mytestdomain.com
Content-Type: application/json
... 
Content-Length: 163

{"LastName":"Doe","FirstName":"Jane","Gender":"Female","MobileNumber":"+1234567890","EmailAddress":"jane.doe@example.com","Job":"Developer","Address":"My address"}

尝试检查从移动设备发送的请求,以确保正确发送。像Fiddler这样的东西。