|
-
Jun 30th, 2023, 02:05 AM
#1
Thread Starter
Hyperactive Member
Web API Giving Error
hi
i have been trying this for a week now but cant find any solution so putting here now.
i have a Xamarin App which sends data to web api.
now the prob is its giving me the below error :
Code:
m_Exception = {System.Net.Http.HttpRequestException: Response status code does not indicate success: 405 (Method Not Allowed).
at System.Net.Http.HttpResponseMessage.EnsureSuccessStatusCode
my Xamarin Code is as under :
Code:
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using Newtonsoft.Json;
using SQLite;
using UmcComplaintManagement.Models;
//using UmcComplaintManagement.ViewModel;
using Xamarin.Forms;
using Xamarin.Forms.PlatformConfiguration.iOSSpecific;
using Xamarin.Forms.Xaml;
using Newtonsoft.Json.Linq;
using System.IO;
using System.Net;
using System.Threading.Tasks;
using Xamarin.Essentials;
using System.Text.RegularExpressions;
namespace UmcComplaintManagement.Pages
{
[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class RegisterUser : ContentPage
{
List<GenderList> GenderList = new List<GenderList>();
public RegisterUser()
{
InitializeComponent();
GenderList.Add(new GenderList { Gender = "Male" });
GenderList.Add(new GenderList { Gender = "Female" });
GenderList.Add(new GenderList { Gender = "Transgender" });
cmbGender.ItemsSource = GenderList;
}
private void TapGestureRecognizer_Tapped(object sender, EventArgs e)
{
//await Browser.OpenAsync("http://www.water.umcgov.in/ViewConsumerDetails.aspx", BrowserLaunchMode.SystemPreferred);
}
private async Task<bool> IsNetworkAvailable()
{
var current = Connectivity.NetworkAccess;
if (current == NetworkAccess.Internet)
{
// Network is available
return true;
}
else
{
// Network is not available
return false;
}
}
private async void btnRegister_Clicked(object sender, EventArgs e)
{
if (!await IsNetworkAvailable())
{
// Network is not available, show a message box
await DisplayAlert("No Network", "No network connection available.", "OK");
return;
}
string emailPattern = "^(?(\")(\".+?(?<!\\\\)\"@)|(([0-9a-z]((\\.(?!\\.))|[-!#\\$%&'\\*\\+/=\\?\\^`\\{\\}\\|~\\w])*)(?<=[0-9a-z])@))(?(\\[)(\\[(\\d{1,3}\\.){3}\\d{1,3}\\])|(([0-9a-z][-\\w]*[0-9a-z]*\\.)+[a-z0-9][\\-a-z0-9]{0,22}[a-z0-9]))$";
string mGender = ((GenderList)cmbGender.SelectedItem).Gender;
string mTitle = ((TitleList)cmbTitle.SelectedItem).Title;
bool isError = false;
if (string.IsNullOrWhiteSpace(mGender))
{
isError = true;
await DisplayAlert("Error", "Please Select The Gender", "OK");
return;
}
if (string.IsNullOrWhiteSpace(mTitle))
{
isError = true;
await DisplayAlert("Error", "Please Select The Title", "OK");
return;
}
if (string.IsNullOrWhiteSpace(txtEmailID.Text))
{
isError = true;
await DisplayAlert("Error", "Please Enter The Email ID", "OK");
return;
}
//if (Regex.IsMatch(txtEmailID.Text, emailPattern))
//{
// isError = true;
// await DisplayAlert("Error", "Please Enter The Valid Email ID", "OK");
// return;
//}
if (string.IsNullOrWhiteSpace(txtFName.Text))
{
isError = true;
await DisplayAlert("Error", "Please Enter The First Name", "OK");
return;
}
if (string.IsNullOrWhiteSpace(txtMiddleName.Text))
{
txtMiddleName.Text = " ";
}
if (string.IsNullOrWhiteSpace(txtLastName.Text))
{
isError = true;
await DisplayAlert("Error", "Please Enter The Last Name", "OK");
return;
}
if (Android.Util.Patterns.Phone.Matcher(txtMobileNo.Text).Matches() == false)
{
isError = true;
await DisplayAlert("Error", "Please Enter Valid Mobile No.", "OK");
return;
}
if (string.IsNullOrWhiteSpace(txtPassword.Text))
{
isError = true;
await DisplayAlert("Error", "Please Enter The Password", "OK");
return;
}
if (string.IsNullOrWhiteSpace(txtPassword2.Text))
{
isError = true;
await DisplayAlert("Error", "Please Enter The Confirmation Password", "OK");
return;
}
if (txtPassword.Text != txtPassword2.Text)
{
isError = true;
await DisplayAlert("Error", "Please The Password And Confirmation Password Do Not Match", "OK");
return;
}
if (isError == false)
{
Registration registration = new Registration()
{
Title = mTitle,
FirstName = txtFName.Text,
MiddleName = txtMiddleName.Text,
LastName = txtLastName.Text,
FullName = txtFName.Text + " " + txtMiddleName.Text + " " + txtLastName.Text,
MobileNo = txtMobileNo.Text,
DateOfBirth = calDateOfBirth.Date,
Gender = mGender,
IsVerified = false,
IsActive = false,
EMailID = txtEmailID.Text,
Password = txtPassword.Text
};
string mCustNo = "W20000217";
string jsonData = JsonConvert.SerializeObject(registration);
var httpClient = new HttpClient();
//var response = await httpClient.GetStringAsync(AppSettings.ApiUrl + "Consumer/GetConsumerDetailsJSonInList?xCustNo=" + mCustNo); --> This works fine and get the data too. but this i did for trial.
var response = await httpClient.GetStringAsync(AppSettings.ApiUrl + "Registration/UserRegistration?xData=" + mCustNo);
if (response == "OK")
{
await DisplayAlert("Registered Successfully", "Verification Email Sent To Your Email ID. Please Verify And Login", "OK");
Navigation.PushModalAsync(new Login());
}
}
// string loginUpload = JsonConvert.SerializeObject(loginInfo);
}
//private void cmbGender_SelectedIndexChanged(object sender, EventArgs e)
//{
// var selectedGender = cmbGender.SelectedIndex;
// //string mGCode = GenderList[selectedGender].GCode;
//}
private void btnReturn_Clicked(object sender, EventArgs e)
{
Navigation.PushModalAsync(new Login());
}
private void TapBack_Tapped(object sender, EventArgs e)
{
Navigation.PopModalAsync();
}
}
}
my WebAPI code is as below :
Code:
Imports System.Net
Imports System.Web.Http
Imports System.Data
Imports System.Data.SqlClient
Imports Newtonsoft.Json
Imports System.Web.Security
'Imports WaterWebServiceFinal.clsCrypto
Namespace Controllers
<RoutePrefix("api/Registration")>
Public Class RegistrationController
Inherits ApiController
Public MyConConnection As New SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings("SqlConnectionString").ToString())
Dim mCmd As String
<Route("UserRegistration")>
Public Function UserRegistration(ByVal xData As String) As String
'Dim mTitle As String
'Dim mFirstName As String
'Dim mMiddleName As String
'Dim mLastName As String
'Dim mFullName As String
'Dim mMobileNo As String
'Dim mGender As String
'Dim mDateOfBirth As Date
'Dim mIsVerified As Boolean
'Dim mIsActive As Boolean
'Dim mEMailID As String
'Dim mPassword As String
'Public Function UserRegistration(ByVal xData As List(Of RegisterUserComplaint)) As String
Dim mResponse As String = "OK"
'Try
' 'For Each aPart As RegisterUserComplaint In xData
' ' mTitle = aPart.Title
' ' mFirstName = aPart.FirstName
' ' mMiddleName = aPart.MiddleName
' ' mLastName = aPart.LastName
' ' mFullName = aPart.FullName
' ' mMobileNo = aPart.MobileNo
' ' mGender = aPart.Gender
' ' mDateOfBirth = aPart.DateOfBirth
' ' mIsVerified = aPart.IsVerified
' ' mIsActive = aPart.IsActive
' ' mEMailID = aPart.EMailID
' ' mPassword = aPart.Password
' 'Next
' mResponse = "OK"
'Catch ex As Exception
' mResponse = ex.Message.ToString
'End Try
'MyConConnection.Close()
Return mResponse
End Function
End Class
End Namespace
Ths Web API code for the working Call i.e. //var response = await httpClient.GetStringAsync(AppSettings.ApiUrl + "Consumer/GetConsumerDetailsJSonInList?xCustNo=" + mCustNo);
is as below :
Code:
Imports System.Net
Imports System.Web.Http
Imports System.Data
Imports System.Data.SqlClient
Imports Newtonsoft.Json
Imports System.Web.Security
Imports WaterWebServiceFinal.clsCrypto
Namespace Controllers
<RoutePrefix("api/Consumer")>
Public Class ConsumerController
Inherits ApiController
Public MyConConnection As New SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings("SqlConnectionString").ToString())
Dim mCmd As String
Public objCrypt As New clsCrypto
<Route("GetConsumerDetails")>
Public Function GetConsumerDetails(ByVal xCustNo As String) As String
mCmd = "SELECT * FROM ConsumerMaster WHERE CustNo = @mCNo"
Dim da_Temp As New SqlDataAdapter(mCmd, MyConConnection)
da_Temp.SelectCommand.Parameters.AddWithValue("@mCNo", xCustNo)
Dim ds_Temp As New DataSet
Dim dTab As New DataTable
da_Temp.Fill(ds_Temp, "ConsumerMaster")
dTab = ds_Temp.Tables("ConsumerMaster")
Dim iRowCount As Integer = dTab.Rows.Count - 1
If iRowCount >= 0 Then
For i As Integer = 0 To iRowCount
Dim iRow As DataRow = dTab.Rows(i)
'Dim xPass As String = objCrypt.DecryptString128Bit(iRow!Password, "abc")
'If xPass = xPassword Then
Dim json As String = JsonConvert.SerializeObject(dTab)
Return json ' JsonConvert.SerializeObject(dTab)
'Else
'Return "Wrong Password"
'End If
Next
Else
Return "Wrong User"
End If
End Function
<Route("GetConsumerDetailsJSonInList")>
Public Function GetConsumerJSonData(ByVal xCustNo As String) As List(Of ConsumerForLogin)
Dim employeeData As List(Of ConsumerForLogin) = New List(Of ConsumerForLogin)()
''employeeData.Add({1, "sdfshfkhsdkhf", "kjhkdfsdf", "sdfjsdkfsf", "sdfjskjfksf"})
'employeeData.Add(New ConsumerForLogin() With {
' .MyId = 1,
' .CustNo = "CustNo",
' .Name = "Consumer Name",
' .Address = "Address ",
' .MobileNo = "MobileNo"
'})
'Return employeeData
Dim mcmd As String = ""
mcmd = "SELECT CM.*, CampMaster.Name As Camp, MM.Name As MeterSize, ST.Name As SupplyTypeName, "
mcmd = mcmd & " SCM.Name As SupplyCategoryName, MT.Name As MeterTypeName, S.Name As StatusName "
mcmd = mcmd & " FROM ConsumerMaster CM "
mcmd = mcmd & " INNER JOIN CampMaster CampMaster ON CM.CampCode = CampMaster.Code "
mcmd = mcmd & " INNER JOIN MeterMaster MM ON CM.Meter_Size = MM.Code "
mcmd = mcmd & " INNER JOIN SupplyType ST ON CM.SupplyType = ST.Code "
mcmd = mcmd & " INNER JOIN SupplyCategoryMaster SCM ON CM.SupplyCategory = SCM.Code "
mcmd = mcmd & " INNER JOIN MeterTypeMaster MT ON CM.MeterType = MT.Code "
mcmd = mcmd & " INNER JOIN Status S ON CM.StatusCode = S.Code "
mcmd = mcmd & " WHERE CM.CustNo = @mCNo "
Dim da_Temp As SqlDataAdapter = New SqlDataAdapter(mcmd, MyConConnection)
da_Temp.SelectCommand.Parameters.AddWithValue("@mCNo", xCustNo)
Dim ds_Temp As DataSet = New DataSet()
Dim dTab As DataTable = New DataTable()
da_Temp.Fill(ds_Temp, "ConsumerMaster")
dTab = ds_Temp.Tables("ConsumerMaster")
Dim iRowCount As Integer = dTab.Rows.Count - 1
Dim mName As String = ""
If iRowCount < 0 Then
mName = "User Not Found"
End If
If iRowCount >= 0 Then
For i As Integer = 0 To iRowCount
Dim irow As DataRow = dTab.Rows(i)
'Dim xmyId As Integer = Convert.ToUInt16(irow("myID").ToString())
mName = irow!Name
employeeData.Add(New ConsumerForLogin() With {
.MyId = irow!MyID,
.CustNo = irow!CustNo,
.Name = irow!Name,
.Address = irow!Address,
.MobileNo = IIf(IsDBNull(irow!MobileNo), " ", irow!MobileNo),
.EMailID = IIf(IsDBNull(irow!EMailID), " ", irow!EMailID),
.Camp = irow!Camp,
.Balance = irow!Balance,
.DpcBal = irow!DpcBal,
.TotalOst = irow!Balance + irow!DpcBal,
.MeterNo = irow!MeterNo,
.Status = irow!StatusName,
.MeterSize = irow!MeterSize,
.SupplyType = irow!SupplyTypeName,
.SupplyCategory = irow!SupplyCategoryName,
.MeterType = irow!MeterTypeName
})
Next
Else
employeeData.Add(New ConsumerForLogin() With {
.MyId = 0,
.CustNo = " ",
.Name = mName,
.Address = " ",
.MobileNo = " ",
.EMailID = " ",
.Camp = " ",
.Balance = 0,
.DpcBal = 0,
.TotalOst = 0,
.MeterNo = " ",
.Status = " ",
.MeterSize = " ",
.SupplyType = " ",
.SupplyCategory = " ",
.MeterType = " "
})
End If
Return employeeData
End Function
End Class
End Namespace
if u see i am not doing anything in UserRegistration function to just check it but even then i am getting the error :
Code:
m_Exception = {System.Net.Http.HttpRequestException: Response status code does not indicate success: 405 (Method Not Allowed).
at System.Net.Http.HttpResponseMessage.EnsureSuccessStatusCode
pls. help me out. i am totally confused as to where i am making mistake.
thanks in advance.
The only time you run out of chances is when you stop taking them.
The mind is like a parachute.
It doesn’t work unless it’s open.
Tags for this Thread
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|