简体   繁体   English

如何使用 Web API 将 Xamarin 与 SQL Server 配合使用

[英]How to work Xamarin with SQL Server using Web API

I am trying to connect to SQL Server with Xamarin using Web API, but I don't know somehow I am doing something wrong here is my code,我正在尝试使用 Web API 使用 Xamarin 连接到 SQL Server,但我不知道我做错了什么,这是我的代码,

Webapi controller 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 Activity 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();
        }
    }
}

i want to work on local sql server not with azure, this code should save username and password to my local sql server, but when i click on button to save its give me this error我想在不使用 azure 的本地 sql 服务器上工作,此代码应该将用户名和密码保存到我的本地 sql 服务器,但是当我单击按钮保存它时,给我这个错误

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

Edit your WebApiConfig.cs File & Change the Route Template as like this,像这样编辑您的 WebApiConfig.cs 文件并更改路由模板,

routeTemplate: "api/{controller}/{action}/{id}"路由模板:“api/{controller}/{action}/{id}”

Hope it works.希望它有效。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Xamarin表单-如何使用SQL Server Web API上传和检索图像 - Xamarin form - how to upload and retrieve image using sql server web api 如何在Xamarin中使用SQL Server LocalDB? - How to work with SQL Server LocalDB in Xamarin? 使用Azure SQL Server创建Web API - Creating Web API Using Azure SQL Server 如何使用Xamarin和SQL Server从数据库下载pdf - How to download pdf from database using Xamarin and SQL Server 如何使用Xamarin和SQL Server在数据库中的浏览器中显示pdf - How to display pdf in browser from database using Xamarin and SQL Server 如何使用Web API在SQL Server中下载以字节形式存储的图像文件 - How to download image file stored in the form of bytes in SQL server using Web API 如何将 Web API 项目从 EntityFramework.InMemory 转换为使用 SQL 服务器? - How to convert Web API project from EntityFramework.InMemory to using SQL Server? 在单个Web API请求中使用MySQL和SQL Server上下文 - Using MySQL and SQL Server contexts in single Web API request 使用Web Api,成员资格提供程序和SQL Server 2012的身份验证服务 - Auth service using Web Api, membership provider, and SQL Server 2012 使用 SQL 服务器模拟从 Web API 方法返回 IQueryable - Returning IQueryable from Web API methods using SQL Server Impersonation
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM