无法在ASP.NET MVC中点击创建的Post API

时间:2017-08-25 08:15:32

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

我有一个用于注册用户的API。

这是Api的代码。

public class AccountsController : ApiController
{
    [HttpPost]
    [ActionName("Register")]
    public HttpResponseMessage Register(string SystemKey, string IPAddress, [FromUri]DomainModels.InstaUser.User user)
    {
        SessionUser _user = new SessionUser(user);
        if (!ValidateSystemKey(SystemKey))
        {
            return Request.CreateErrorResponse(HttpStatusCode.Unauthorized, "Invalid Security Key");
        }
        else if (string.IsNullOrWhiteSpace(IPAddress))
        {
            return Request.CreateErrorResponse(HttpStatusCode.Unauthorized, "Invalid IP Address");
        }
        else if (Models.User.AlreadyExists(user.Username))
        {
            return Request.CreateErrorResponse(HttpStatusCode.Conflict, "Username already registered");
        }
        else if (Models.User.AlreadyExistsPhone(user.Phone))
        {
            return Request.CreateErrorResponse(HttpStatusCode.Conflict, "Phone Number already registered");
        }
        else if (DomainModels.InstaUser.User.Register(user, IPAddress))
        {
            CreateTokens(_user, IPAddress);
            return Request.CreateResponse(HttpStatusCode.OK, user);
        }
        else
        {
            return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, "Unable to register user due to techincal issues");
        }
    }
}

这是路线

///{SystemKey}/{IPAddress}/{Username}/{Password}/{Name}/{Email}/{Phone}/{Type}
        config.Routes.MapHttpRoute(
           name: "Register",
           routeTemplate: "api/Accounts/Register",
           defaults: new { controller = "Accounts", action = "Register", SystemKey = RouteParameter.Optional, IPAddress = RouteParameter.Optional, Username = RouteParameter.Optional, Password = RouteParameter.Optional, Name = RouteParameter.Optional,  Email = RouteParameter.Optional, Phone = RouteParameter.Optional, Type = RouteParameter.Optional }
           );

我也尝试过添加和删除可选参数。

这就是我试图击中它的方式。

        Dictionary<string, string> Params = new Dictionary<string, string>();
        Params.Add("SystemKey", ServerConfig.SystemKey);
        Params = Params.Union(Common.ConvertToDictionary(data)).ToDictionary(x=>x.Key, x =>x.Value); // data is a SessionUser object that i am taking input
        using (HttpClient client = new HttpClient())
        {
            var parameters = new FormUrlEncodedContent(nameValueCollection: Params);
            string Path = ServerConfig.server_path + "api/Accounts/Register";
            var response = client.PostAsJsonAsync(Path, parameters).Result;
            //var response = client.PostAsync(Path, parameters).Result; both give same response of 404

        }

API没有被点击,响应包含404 Not found。

我能用邮递员打api。但是c#代码没有击中api。

0 个答案:

没有答案