c# - WebApi 创建无法从 Xamarin.Android 运行的用户

标签 c# asp.net azure xamarin xamarin.android

我尝试使用 Web api 在 xamarin.android 的 sql azure 中创建新用户。但每次我尝试创建新用户时都会收到此错误消息

{"$id":"1","message":"No HTTP resource was found that matches the request URI 'http://xamari/nlogin20170612105003.azurewebsites.net/api/Login'.","messageDetail":"No action was found 

因此提供此 Web api 来进行身份验证并创建新用户,我的登录正常,没有错误,但是当我创建新用户时,我收到了该错误消息。

这是我的 Web API Controller :

  using System;  
    using System.Collections.Generic;  
    using System.Linq;  
    using System.Net;  
    using System.Net.Http;  
    using System.Web.Http;  
    using XamarinLogin.Models;  
    namespace XamarinLogin.Controllers  
    [RoutePrefix("api/Login")]
    {  
        public class LoginController: ApiController  
        {  
            xamarinloginEntities db = new xamarinloginEntities();  
            /  
            [HttpPost]  
            [ActionName("XAMARIN_REG")]  
            // POST: api/Login  
            public HttpResponseMessage Xamarin_reg(string username, string password)  
            {  
                Login login = new Login();  
                login.Username = username;  
                login.Password = password;  
                db.Logins.Add(login);  
                db.SaveChanges();  
                return Request.CreateResponse(HttpStatusCode.Accepted, "Successfully Created");  
            }  
            [HttpGet]  
            [ActionName("XAMARIN_Login")]  
            // GET: api/Login/5  
            public HttpResponseMessage Xamarin_login(string username, string password)  
            {  
                var user = db.Logins.Where(x => x.Username == username && x.Password == password).FirstOrDefault();  
                if (user == null)  
                {  
                    return Request.CreateResponse(HttpStatusCode.Unauthorized, "Please Enter valid UserName and Password");  
                }  
                else  
                {  
                    return Request.CreateResponse(HttpStatusCode.Accepted, "Success");  
                }  
            }  
        }  
    }  

这是我在 xamarin.android 中创建用户脚本:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Http;
using System.Net.Http.Headers;
using Newtonsoft.Json;
using Android.App;
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Views;
using Android.Widget;

namespace LoginAzureDroid
{

    public class NewUserActivity : Activity
    {
        EditText txtusername;
        EditText txtPassword;
        Button btncreate;
        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);
            // Create your application here  
            SetContentView(Resource.Layout.Reg);
            txtusername = FindViewById<EditText>(Resource.Id.txtsaveusername);
            txtPassword = FindViewById<EditText>(Resource.Id.txtsavepassword);
            btncreate = FindViewById<Button>(Resource.Id.btnsavecreate);
            btncreate.Click += Btncreate_Click;
        }
        private async void Btncreate_Click(object sender, EventArgs e)
        {
            Login log = new Login();
            log.username = txtusername.Text;
            log.password = txtPassword.Text;
            HttpClient client = new HttpClient();
            string url = "http://xamarinlogin20170612105003.azurewebsites.net/api/Login";
            var uri = new Uri(url);
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
            HttpResponseMessage response;
            var json = JsonConvert.SerializeObject(log);
            var content = new StringContent(json, Encoding.UTF8, "application/json");
            response = await client.PostAsync(uri, content);
            if (response.StatusCode == System.Net.HttpStatusCode.Accepted)
            {
                var errorMessage1 = response.Content.ReadAsStringAsync().Result.Replace("\\", "").Trim(new char[1]
                {
                '"'
                });
                Toast.MakeText(this, errorMessage1, ToastLength.Long).Show();
            }
            else
            {
                var errorMessage1 = response.Content.ReadAsStringAsync().Result.Replace("\\", "").Trim(new char[1]
                {
                '"'
                });
                Toast.MakeText(this, errorMessage1, ToastLength.Long).Show();
            }
        }
    }
}

那么我的错在哪里,是我的网址吗?我在 web api 中的代码?或我在 xamarin.android 中的代码。

最佳答案

{"$id":"1","message":"No HTTP resource was found that matches the request URI 'http://xamari/nlogin20170612105003.azurewebsites.net/api/Login'.","messageDetail":"No action was found

根据您的代码,您为 LoginController 添加了 RoutePrefix,我假设您需要为每个操作或您的操作添加路由属性,如下所示:

[HttpPost]  
[Route("XAMARIN_REG")]  
// POST: api/Login/XAMARIN_REG
public HttpResponseMessage Xamarin_reg(string username, string password)
[HttpGet]  
[Route("XAMARIN_Login")]  
// GET: api/Login/XAMARIN_Login?username={username}&password={password}
public HttpResponseMessage Xamarin_login(string username, string password)  

要创建新用户,您需要更改网址,如下所示:

string url = "http://xamarinlogin20170612105003.azurewebsites.net/api/Login/XAMARIN_REG";

另外,您可以引用Attribute Routing in ASP.NET Web API 2了解更多详情。

更新:

您可以按如下方式定义用户注册的 View 模型:

public class RegUser
{
  public string username {get;set;}
  public string password {get;set;}
}

[RoutePrefix("api/Login")]
public class LoginController : ApiController
{
    [HttpPost]
    [Route("regUser")]
    public string newUser(RegUser user)
    {
        return user.username + "_" + user.password;
    }
}

enter image description here

此外,这里有一篇关于 pass multiple parameters to Web API controller methods 的博客,多种方法可以引用。

关于c# - WebApi 创建无法从 Xamarin.Android 运行的用户,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44511488/

相关文章:

c# - 拦截 NHibernate Lazy-Load 行为以在未连接到 session 时返回 null?

c# - 如何将空白文本框值作为 null 传递给绑定(bind)日期时间

c# - Nlog Date布局需要获取长日期的日期时间偏移量

javascript - 对 JavaScript 文件的动态引用

asp.net - WebFormsMVP 的缺点?

java - 我想看一个从 aspx webservice 传递对象数组的示例 web 方法

php - Sendgrid Azure PHP

c# - 如何在 Visual Studio 中查找两个 .cs 文件之间的差异

Azure DevOps 自定义规则 - 当状态更改时将 Bug 分配给 @me

Azure Databricks - 监视作业集群的启动或关闭状态