【问题标题】:How to work Xamarin with SQL Server using Web API如何使用 Web API 将 Xamarin 与 SQL Server 一起使用
【发布时间】:2018-03-25 20:22:05
【问题描述】:

我正在尝试使用 Web API 通过 Xamarin 连接到 SQL Server,但我不知道我做错了什么,这是我的代码,

Webapi 控制器

public class LoginController : ApiController
{
    UserEntities db = new UserEntities();  

    [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 活动

public class MainActivity : Activity
    {

    EditText txtusername;
    EditText txtPassword;
    Button btncreate;
    protected override void OnCreate(Bundle savedInstanceState)
    {

        base.OnCreate(savedInstanceState);
        // Create your application here  
        SetContentView(Resource.Layout.Main);
        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://localhost:54445/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();
        }
    }
}

我想在本地 sql 服务器上工作,而不是使用 azure, 此代码应将用户名和密码保存到我的本地 sql 服务器,但是当我单击按钮保存时,会出现此错误

System.Net.Http.HttpRequestException: An error occurred while sending the request

【问题讨论】:

  • 请不要自行进行身份验证——很难以安全可靠的方式进行身份验证。您可以使用许多现成的身份验证框架。
  • 我知道,我只是想测试将任何数据保存在数据库中,这仅用于测试目的
  • 首先,使用 Postman 之类的工具来测试您的 WebApi,这样您就可以排除该层与您的客户端层中的任何问题。其次,不要使用本地主机。使用您的服务器的 IP 或 FQDN。
  • 我已经用邮递员测试过它在那里也不能正常工作以及如何使用 ip 或 fqdn?
  • 我还测试了在邮递员工具中运行 webapi 我收到此错误{ "$id": "1", "message": "No HTTP resource was found that matches the request URI 'http://localhost:54445/api/Login'.", "messageDetail": "No action was found on the controller 'Login' that matches the request." }

标签: c# sql-server xamarin asp.net-web-api xamarin.forms


【解决方案1】:

像这样编辑您的 WebApiConfig.cs 文件并更改路由模板,

routeTemplate: "api/{controller}/{action}/{id}"

希望它有效。

【讨论】:

  • 我已经尝试过这个网址我收到了这个错误{ "$id": "1", "message": "No HTTP resource was found that matches the request URI 'http://localhost:54445/api/Login'.", "messageDetail": "No action was found on the controller 'Login' that matches the request." }
猜你喜欢
  • 1970-01-01
  • 2015-12-22
  • 2019-11-15
  • 1970-01-01
  • 1970-01-01
  • 2012-12-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多