У меня возникли проблемы с моим API в формах xamarin, я все настроил, но это не работает
в форме (запуск приложения на моем физическом телефоне Android), и появляется сообщение Exception: InternalServerError
MainPage.xaml:
MainPage.xaml.cs:
using Newtonsoft.Json;
using PFAG1_2Cars.Core.Entities; // Use the namespace where your Marque class is defined
using System;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using Xamarin.Forms;
namespace TEST
{
public partial class MainPage : ContentPage
{
private readonly HttpClient _httpClient;
public MainPage()
{
InitializeComponent();
_httpClient = new HttpClient();
_httpClient.BaseAddress = new Uri("http://192.168.x.x:5050/api/");
}
private async void OnSubmitClicked(object sender, EventArgs e)
{
var marque = new Marque
{
IdMarque = int.Parse(IdMarqueEntry.Text),
NomMarque = NomMarqueEntry.Text
};
var json = JsonConvert.SerializeObject(marque);
var content = new StringContent(json, Encoding.UTF8, "application/json");
try
{
var response = await _httpClient.PostAsync("your", content);
if (response.IsSuccessStatusCode)
{
ResultLabel.Text = "Marque added successfully!";
}
else
{
ResultLabel.Text = $"Error: {response.StatusCode}";
}
}
catch (Exception ex)
{
ResultLabel.Text = $"Exception: {ex.Message}";
}
}
}
}
App.xaml.cs:
using System;
using Xamarin.Forms;
using Microsoft.Extensions.DependencyInjection;
using PFAG1_2Cars.Core.Services;
using PFAG1_2Cars.Data;
using PFAG1_2Cars.Services.Services;
using PFAG1_2Cars.Core;
using PFAG1_2Cars.Data.UnitOfWork;
using PFAG1_2Cars.Data.Repositories;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using System.IO;
using PFAG1_2Cars.Core.Repositories;
namespace TEST
{
public partial class App : Application
{
// Static property to hold the service provider
public static IServiceProvider ServiceProvider { get; private set; }
public App()
{
InitializeComponent();
// Setup dependency injection
ConfigureServices();
// Set the main page as a navigation page containing MainPage
MainPage = new NavigationPage(new MainPage());
}
private void ConfigureServices()
{
var services = new ServiceCollection();
var connectionString = "Server=192.168.x.x\\SQLEXPRESS,1433;Database=xxx;User Id=xxx;Password=xxx;";
// Register DbContext from the data layer with the direct connection string
services.AddDbContext
(options =>
options.UseSqlServer(connectionString));
// Register UnitOfWork and other services if needed
services.AddScoped();
services.AddScoped();
// Register repositories
services.AddScoped();
services.AddScoped();
services.AddScoped();
services.AddScoped();
services.AddScoped();
services.AddScoped();
services.AddScoped();
services.AddScoped();
services.AddScoped();
services.AddScoped();
services.AddScoped();
// Build the service provider
ServiceProvider = services.BuildServiceProvider();
}
protected override void OnStart()
{
// Handle when your app starts
}
protected override void OnSleep()
{
// Handle when your app sleeps
}
protected override void OnResume()
{
// Handle when your app resumes
}
}
}
appsettings.json:
{
"ConnectionStrings": {
"DefaultConnection": "Server=192.168.x.x\\SQLEXPRESS,1433;Database=xxx;User Id=xxx;Password=xxx;Encrypt=False;"
},
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
}
},
"AllowedHosts": "*",
"ApiBaseUrl": "https://192.168.x.x:5050/api/"
}
Я пробовал в Postman и в своем браузере, и все работает отлично, даже в браузере моего телефона.
[img]https:// i.sstatic.net/Yp4NB7x7.png[/img]
YourController.cs:
using Microsoft.AspNetCore.Mvc;
using PFAG1_2Cars.Core;
using PFAG1_2Cars.Core.Entities;
using PFAG1_2Cars.Core.Repositories;
using PFAG1_2Cars.Core.Services;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
namespace Web.API.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class YourController : ControllerBase
{
private readonly IMarqueService _marqueService;
public YourController(IMarqueService marqueService)
{
_marqueService = marqueService;
}
// GET: api/marque
[HttpGet]
public async Task GetMarques()
{
try
{
var marques = await _marqueService.GetAllMarques();
return Ok(marques);
}
catch (Exception ex)
{
return StatusCode(500, $"Internal server error: {ex.Message}");
}
}
// GET: api/marque/5
[HttpGet("{id}")]
public async Task GetMarque(int id)
{
try
{
var marque = await _marqueService.GetMarqueById(id);
if (marque == null)
{
return NotFound();
}
return Ok(marque);
}
catch (Exception ex)
{
return StatusCode(500, $"Internal server error: {ex.Message}");
}
}
// POST: api/marque
[HttpPost]
public async Task PostMarque(Marque marque)
{
try
{
var newMarque = await _marqueService.CreateMarque(marque);
return CreatedAtAction(nameof(GetMarque), new { id = newMarque.IdMarque }, newMarque);
}
catch (Exception ex)
{
return StatusCode(500, $"Internal server error: {ex.Message}");
}
}
// PUT: api/marque/5
[HttpPut("{id}")]
public async Task PutMarque(int id, Marque marque)
{
try
{
await _marqueService.UpdateMarque(new Marque { IdMarque = id }, marque);
return NoContent();
}
catch (Exception ex)
{
return StatusCode(500, $"Internal server error: {ex.Message}");
}
}
// DELETE: api/marque/5
[HttpDelete("{id}")]
public async Task DeleteMarque(int id)
{
try
{
await _marqueService.DeleteMarqueById(id);
return NoContent();
}
catch (Exception ex)
{
return StatusCode(500, $"Internal server error: {ex.Message}");
}
}
}
}
Подробнее здесь: https://stackoverflow.com/questions/786 ... in-android
InternalServiceError при попытке опубликовать форму в xamarin Android ⇐ C#
Место общения программистов C#
1719358764
Anonymous
У меня возникли проблемы с моим API в формах xamarin, я все настроил, но это не работает
в форме (запуск приложения на моем физическом телефоне Android), и появляется сообщение Exception: InternalServerError
MainPage.xaml:
MainPage.xaml.cs:
using Newtonsoft.Json;
using PFAG1_2Cars.Core.Entities; // Use the namespace where your Marque class is defined
using System;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using Xamarin.Forms;
namespace TEST
{
public partial class MainPage : ContentPage
{
private readonly HttpClient _httpClient;
public MainPage()
{
InitializeComponent();
_httpClient = new HttpClient();
_httpClient.BaseAddress = new Uri("http://192.168.x.x:5050/api/");
}
private async void OnSubmitClicked(object sender, EventArgs e)
{
var marque = new Marque
{
IdMarque = int.Parse(IdMarqueEntry.Text),
NomMarque = NomMarqueEntry.Text
};
var json = JsonConvert.SerializeObject(marque);
var content = new StringContent(json, Encoding.UTF8, "application/json");
try
{
var response = await _httpClient.PostAsync("your", content);
if (response.IsSuccessStatusCode)
{
ResultLabel.Text = "Marque added successfully!";
}
else
{
ResultLabel.Text = $"Error: {response.StatusCode}";
}
}
catch (Exception ex)
{
ResultLabel.Text = $"Exception: {ex.Message}";
}
}
}
}
App.xaml.cs:
using System;
using Xamarin.Forms;
using Microsoft.Extensions.DependencyInjection;
using PFAG1_2Cars.Core.Services;
using PFAG1_2Cars.Data;
using PFAG1_2Cars.Services.Services;
using PFAG1_2Cars.Core;
using PFAG1_2Cars.Data.UnitOfWork;
using PFAG1_2Cars.Data.Repositories;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using System.IO;
using PFAG1_2Cars.Core.Repositories;
namespace TEST
{
public partial class App : Application
{
// Static property to hold the service provider
public static IServiceProvider ServiceProvider { get; private set; }
public App()
{
InitializeComponent();
// Setup dependency injection
ConfigureServices();
// Set the main page as a navigation page containing MainPage
MainPage = new NavigationPage(new MainPage());
}
private void ConfigureServices()
{
var services = new ServiceCollection();
var connectionString = "Server=192.168.x.x\\SQLEXPRESS,1433;Database=xxx;User Id=xxx;Password=xxx;";
// Register DbContext from the data layer with the direct connection string
services.AddDbContext
(options =>
options.UseSqlServer(connectionString));
// Register UnitOfWork and other services if needed
services.AddScoped();
services.AddScoped();
// Register repositories
services.AddScoped();
services.AddScoped();
services.AddScoped();
services.AddScoped();
services.AddScoped();
services.AddScoped();
services.AddScoped();
services.AddScoped();
services.AddScoped();
services.AddScoped();
services.AddScoped();
// Build the service provider
ServiceProvider = services.BuildServiceProvider();
}
protected override void OnStart()
{
// Handle when your app starts
}
protected override void OnSleep()
{
// Handle when your app sleeps
}
protected override void OnResume()
{
// Handle when your app resumes
}
}
}
appsettings.json:
{
"ConnectionStrings": {
"DefaultConnection": "Server=192.168.x.x\\SQLEXPRESS,1433;Database=xxx;User Id=xxx;Password=xxx;Encrypt=False;"
},
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
}
},
"AllowedHosts": "*",
"ApiBaseUrl": "https://192.168.x.x:5050/api/"
}
Я пробовал в Postman и в своем браузере, и все работает отлично, даже в браузере моего телефона.
[img]https:// i.sstatic.net/Yp4NB7x7.png[/img]
YourController.cs:
using Microsoft.AspNetCore.Mvc;
using PFAG1_2Cars.Core;
using PFAG1_2Cars.Core.Entities;
using PFAG1_2Cars.Core.Repositories;
using PFAG1_2Cars.Core.Services;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
namespace Web.API.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class YourController : ControllerBase
{
private readonly IMarqueService _marqueService;
public YourController(IMarqueService marqueService)
{
_marqueService = marqueService;
}
// GET: api/marque
[HttpGet]
public async Task GetMarques()
{
try
{
var marques = await _marqueService.GetAllMarques();
return Ok(marques);
}
catch (Exception ex)
{
return StatusCode(500, $"Internal server error: {ex.Message}");
}
}
// GET: api/marque/5
[HttpGet("{id}")]
public async Task GetMarque(int id)
{
try
{
var marque = await _marqueService.GetMarqueById(id);
if (marque == null)
{
return NotFound();
}
return Ok(marque);
}
catch (Exception ex)
{
return StatusCode(500, $"Internal server error: {ex.Message}");
}
}
// POST: api/marque
[HttpPost]
public async Task PostMarque(Marque marque)
{
try
{
var newMarque = await _marqueService.CreateMarque(marque);
return CreatedAtAction(nameof(GetMarque), new { id = newMarque.IdMarque }, newMarque);
}
catch (Exception ex)
{
return StatusCode(500, $"Internal server error: {ex.Message}");
}
}
// PUT: api/marque/5
[HttpPut("{id}")]
public async Task PutMarque(int id, Marque marque)
{
try
{
await _marqueService.UpdateMarque(new Marque { IdMarque = id }, marque);
return NoContent();
}
catch (Exception ex)
{
return StatusCode(500, $"Internal server error: {ex.Message}");
}
}
// DELETE: api/marque/5
[HttpDelete("{id}")]
public async Task DeleteMarque(int id)
{
try
{
await _marqueService.DeleteMarqueById(id);
return NoContent();
}
catch (Exception ex)
{
return StatusCode(500, $"Internal server error: {ex.Message}");
}
}
}
}
Подробнее здесь: [url]https://stackoverflow.com/questions/78669840/internalserviceerror-while-trying-to-post-though-a-form-in-xamarin-android[/url]
Ответить
1 сообщение
• Страница 1 из 1
Перейти
- Кемерово-IT
- ↳ Javascript
- ↳ C#
- ↳ JAVA
- ↳ Elasticsearch aggregation
- ↳ Python
- ↳ Php
- ↳ Android
- ↳ Html
- ↳ Jquery
- ↳ C++
- ↳ IOS
- ↳ CSS
- ↳ Excel
- ↳ Linux
- ↳ Apache
- ↳ MySql
- Детский мир
- Для души
- ↳ Музыкальные инструменты даром
- ↳ Печатная продукция даром
- Внешняя красота и здоровье
- ↳ Одежда и обувь для взрослых даром
- ↳ Товары для здоровья
- ↳ Физкультура и спорт
- Техника - даром!
- ↳ Автомобилистам
- ↳ Компьютерная техника
- ↳ Плиты: газовые и электрические
- ↳ Холодильники
- ↳ Стиральные машины
- ↳ Телевизоры
- ↳ Телефоны, смартфоны, плашеты
- ↳ Швейные машинки
- ↳ Прочая электроника и техника
- ↳ Фототехника
- Ремонт и интерьер
- ↳ Стройматериалы, инструмент
- ↳ Мебель и предметы интерьера даром
- ↳ Cантехника
- Другие темы
- ↳ Разное даром
- ↳ Давай меняться!
- ↳ Отдам\возьму за копеечку
- ↳ Работа и подработка в Кемерове
- ↳ Давай с тобой поговорим...
Мобильная версия